我有 2 個陣列:
int element[3] = {0, 1, 2};
int quantity[3] = {2, 3, 4};
現在我想要一個包含兩個零、三個一和四個二的結果陣列。
int result[2 3 4] = {0, 0, 1, 1, 1, 2, 2, 2, 2};
我如何使用回圈來做到這一點?
uj5u.com熱心網友回復:
您需要計算結果陣列中的元素數量,并宣告一個具有計算值的可變長度陣列或動態分配這樣的陣列。
例如
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 ) );
然后在嵌套回圈中,您需要填充結果陣列。
例如
for ( size_t i = 0, j = 0; i < 3; i )
{
for ( size_t k = 0; k < quantity[i]; k )
{
result[j ] = element[i];
}
}
uj5u.com熱心網友回復:
首先我們需要計算結果陣列的大小。然后開始一次填充每個元素的結果陣列。當我們填充結果陣列時,我們需要增加索引。
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]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520271.html
下一篇:結構內部元素的值賦值在c中失敗
