簡體   English   中英

使用數組並求和

[英]Using arrays and inverting their sums

我希望總和為a [0] + b [3],a [1] + b [2],依此類推(直到a [3]和b [0]),但我似乎無法讓我的代碼正常工作。 下面是執行a [0] + b [0]的代碼。 關於如何更改代碼以獲得所需輸出的任何想法? 我試圖改變我的總和

#include <stdio.h>

#include <math.h>

#define SIZE 4

int main()

{

    int i;

    int sum[SIZE];

    int a[SIZE] = { 2, 3, 5, 8 };

    int b[SIZE] = { 1, 0, 4, 6 };


for (i = 0; i < SIZE; ++i)

{

    printf("Enter a[%d] \n", i);

    scanf_s("%d", &a[i]);

}

for (i = 3; i < SIZE; --i)

{
    printf("Enter b[%d] \n", i);

    scanf_s("%d", &b[i]);

    {
        if (i == 0)
            break;
    }
}

for (i = 0; i < SIZE; i++)

{

    printf("c[%d] = %d and d[%d] = %d\n", i, a[i], i, b[i]);

}

    sum[SIZE] = 0;

    for (i = 0; i < SIZE; i++)

    {
        sum[i] = a[i] + b[i];  //I tried writing individual statements for each by using sum [0] = a[3] + b[0] etc. but that didn't work
    }


for (i = 0; i < SIZE; i++)

{

    printf ("sum[%d] = %d \n", i, sum[i]); // I also tried altering the print statement but that didn't work which is why I resorted back to this original code

}

return 0;

}

嘗試這個 :

for (i = 0; i < SIZE; i++)
{
         sum[i] = a[i] + b[SIZE - i - 1];  
}

您可以使用兩個索引。 在循環中增加一個,同時減少另一個。

int ai = 0;
int bi = SIZE-1;

for ( ; ai < SIZE && bi >= 0; ++ai, --bi )
{
   sum[ai] = a[ai] + b[bi];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM