我编写了一个程序来输入十个数字并分别对奇数和偶数求和,对偶数求和一切都很顺利,但是当涉及奇数时,它会给出其他值......
我尝试了不同的 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/