我需要我的程序来运行,告诉我输入的自然数的和,它还需要和总和一起说,我需要它来显示奇数和偶数的和。
这就是我目前所掌握的,它在C语言中不会正确运行。
#include <stdio.h>
int main (void)
{
int n, i, sum = 0;
int sum1 = 0;
int sum2 = 0;
printf("enter a number and I will tell you the numbers sums.");
scanf("%d", &n);
for(i=1; i<= n; ++n)
{
sum2 = sum2 + n;
}
for(i=2; i<= n; ++n)
{
sum1 = sum1 + n;
}
for(i=1; i<= n; ++n)
{
sum += i;
}
printf("sum of integers is %d" ,sum);
printf("sum of odd integers is %d" ,sum1);
printf("sum of even integers is %d" ,sum2);
return 0;
}
最佳答案
在循环中要计算奇数和偶数,需要在循环中增加2,而不是1。使用++i
,而不是i += 2
:
for (i = 2; i <= n; i += 2)
增量中应该是
i
,而不是n
。您正在更改最终变量的值。此外,除非我误解了你的意图,否则你应该把i
加到你的总数中,而不是n
。关于c - C编程加自然数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42126263/