程序应该读取输入的数字并确定它们是偶数还是奇数。
然后它需要显示奇数和偶数,以及输入数字的平均值。它会在输入0
时停止。
我的问题是它只是在输入第一个号码后挂起。
#include "stdio.h"
int main(void)
{
int oddcount = 0, evencount = 0; /* Count of even and odd numbers. */
int number;
float avge = 0, avgo = 0; /* Average for even and odd numbers. */
int evennum = 0, oddnum = 0;
printf("Enter a number or enter 0 to stop: ");
scanf_s("%i", &number);
while(number != 0)
{
if(number % 2 == 0)
{ evencount = evencount + 1;
evennum += number; }
else
{ oddcount = oddcount + 1;
oddnum += number; }
}
if(oddnum != 0)
avgo = oddnum / oddcount; /* Finding the odd average. */
if(evennum != 0)
avge = evennum / evencount; /* Finding the even average. */
printf("Here is the count odd %i and even %i numbers.\n", oddcount, evencount);
printf("And their averages %f odd and %f even.\n", avgo, avge);
return 0;
}
答案 0 :(得分:1)
因为它是一个无限循环...
while(number != 0)
{
if(number % 2 == 0)
{ evencount = evencount + 1;
evennum += number; }
else
{ oddcount = oddcount + 1;
oddnum += number; }
}
在这里,你的while循环引导变量number
永远不会在迭代之间被修改,这使得它保持不变,因此,while条件将永久地重新生成...
可能的解决方案 似乎是: -
int number=1; // just for initialisation with a non-zero number...
while(number != 0)
{
printf("Enter a number or enter 0 to stop: ");
scanf_s("%i", &number);
if(number % 2 == 0)
{ evencount = evencount + 1;
evennum += number; }
else
{ oddcount = oddcount + 1;
oddnum += number; }
}
答案 1 :(得分:1)
在第一个之后你没有读新数字。尝试像
这样的东西while( scanf("%d", &number) == 1 && number != 0){
//Count evens and odds
}
另一种处理此问题的方法是在while循环结束时添加另一个scanf