c - 我在 for 循环内使用 if -else 求和数组中的奇数时遇到问题

标签 c for-loop sum

我编写了一个程序来输入十个数字并分别对奇数和偶数求和,对偶数求和一切都很顺利,但是当涉及奇数时,它会给出其他值......

我尝试了不同的 for 循环来处理偶数和奇数,它也给出了另一个值..

#include<stdio.h>

int main()
{
 int i, a[10];
 int Even_Sum = 0, Odd_Sum = 0;




 for(i =1; i <=10; i++)
 {
      printf("Insert number %d: ",i);
      scanf("%d", &a[i]);
 }

 for(i = 1; i <=10; i ++)
 {
   if(a[i] % 2 == 0)
   {
    Even_Sum = Even_Sum + a[i];
   }
   else
   {
    Odd_Sum = Odd_Sum + a[i];
   }
 }

 printf("\n The Sum of Even Numbers in this Array = %d ", Even_Sum);
 printf("\n The Sum of Odd Numbers in this Array = %d ", Odd_Sum);
 return 0;
}

输入是: 2 3 5 4 6 12 3 7 4 9

我期望的输出是:

The Sum of Even Numbers in this Array = 28
The Sum of Odd Numbers in this Array = 27

最佳答案

数组总是从 0 开始;因此你的范围应该是 0 到 9。

for(i = 0; i < 10; i++)
 {
      printf("Insert number %d: ",i);
      scanf("%d", &a[i]);
 }

 for(i = 0; i < 10; i++)
 {
   if(a[i] % 2 == 0)
   {
    Even_Sum = Even_Sum + a[i];
   }
   else
   {
    Odd_Sum = Odd_Sum + a[i];
   }
 }

关于c - 我在 for 循环内使用 if -else 求和数组中的奇数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57252141/

相关文章:

c - 如何判断对 system() 的调用是否已经退出?

javascript - 如何使用 forEach 循环向下计数 javascript

python - 添加列表元素

MySQL查询返回多个求和列

c - 如何从头开始编写交叉编译器?

c - 一直保持strtok_s的第一个参数为NULL对不对?

c - 为什么即使回调参数与 XML 中的参数不匹配,GObject 方法仍会被调用?

javascript - 在javascript中重新排序数组

javascript - 以设定的时间增量循环对象

list - 总结 Scala 中的选项列表