首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用C语言解决这个数组问题?

如何用C语言解决这个数组问题?
EN

Stack Overflow用户
提问于 2022-10-26 08:57:01
回答 2查看 66关注 0票数 -1

我有两个数组:int element[3] = {0, 1, 2}; int quantity[3] = {2, 3, 4};,现在我想要一个结果数组,它将有两个零,三个1和四个二分之一。int result[2+3+4] = {0, 0, 1, 1, 1, 2, 2, 2, 2};我如何使用循环来完成这个任务?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-26 09:02:36

您需要计算结果数组中的元素数,并使用计算值声明可变长度数组,或者动态分配这样的数组。

例如

代码语言:javascript
复制
int quantity[3] = {2, 3, 4};

size_t n = 0;
for ( size_t i = 0; i < 3; i++ )
{
    n += quantity[i];
}

int result[n];

// or
// int *result = malloc( n * sizeof( int ) );

然后在嵌套循环中,您需要填充结果数组。

例如

代码语言:javascript
复制
for ( size_t i = 0, j = 0; i < 3; i++ )
{
    for ( size_t k = 0; k < quantity[i]; k++ )
    {
        result[j++] = element[i];
    }
}
票数 1
EN

Stack Overflow用户

发布于 2022-10-26 09:21:03

首先,我们需要计算结果数组的大小。然后开始一次填充每个元素的结果数组。在填充结果数组时,需要增加索引。

代码语言:javascript
复制
int elementSize = sizeof(element)/sizeof(element[0]);
int resultSize = 0;

//pre calculating the size of result array
for(int i=0;i<elementSize;i++ ) {
    resultSize += quantity[i];
}

int result[resultSize], currIndex = 0;
//picking each element
for(int i = 0;i< elementSize; i++ ) {
    int currElement = element[i];
    int currQuantity = quantity[i];

//filling the current element required no of times in the result array
    while(currQuantity--) {
        result[currIndex] = currElement;
        currIndex++;
    }
}

//just a for loop to check the elements inside result array
for(int i=0;i<resultSize;i++)
    printf("%d\n",result[i]);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74205056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档