循环的C程序以零零结束
问题如下:
使用f for for以写作0,计算偶数总和,奇数总和
我不知道为什么我的代码不起作用:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i = 0, num[i], sum, even, odd;
for (;;) {
printf("Write a number: ");
scanf("%d", &num[i]);
if (num[i] == 0) {
break;
}
if (num[i] % 2 == 0) {
even += num[i];
} else
odd += num[i];
i++;
}
printf("Sum of even is: %d\n", even);
printf("Sum of odd is: %d", odd);
return 0;
}
The question goes as follows:
Using a for loop ended with writing 0, compute sum of even numbers, sum of odd numbers,
I have no idea why my code isn't working:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i = 0, num[i], sum, even, odd;
for (;;) {
printf("Write a number: ");
scanf("%d", &num[i]);
if (num[i] == 0) {
break;
}
if (num[i] % 2 == 0) {
even += num[i];
} else
odd += num[i];
i++;
}
printf("Sum of even is: %d\n", even);
printf("Sum of odd is: %d", odd);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该数组的零元素声明
调用了不确定的行为。
实际上,没有任何理由为此任务使用数组。
您也需要将变量均匀且奇怪。同样不使用变量总和。
该程序可以使用以下方式,
如果要使用数组,则需要声明具有固定元素数量的数组并限制输入数量。或者,您需要分配和重新分配动态分配的数组。但这使您的程序更加复杂。
This declaration of an array with zero elements
invokes undefined behavior.
Actually there is no any reason to use an array for this task.
Also you need to initialize the variables even and odd. Also the variable sum is not used.
The program can look for example the following way
If you are going to use an array then you need either to declare an array with a fixed number of elements and restrict the number of inputs. Or you need to allocate and reallocate a dynamically allocated array. But this makes your program more complicated with a redundant code.