我想知道是否有人可以帮助我并指出我在这里做错了什么。我的任务是:
Write a program that reads integers until 0 is entered. After input terminates, the program should report the total number of even integers (excluding the 0) entered, the average value of the even integers, the total number of odd integers entered, and the average value of the odd integers
我成功地完成了类似的任务,但使用的是字符(停在“#”而不是 0),并且没有遇到任何问题。我在这里没有看到或缺少什么?
#include <stdio.h>
int evenQ = 0, oddQ = 0, evenSum = 0, oddSum = 0; /* We initate variables */
int ch;
int main(void)
{
while ((ch = getchar()) != 0 ) /* As long as the input is not 0 keep taking input*/
{
if (ch % 2 == 0) /* If the input is an even integer */
{
evenQ++; /* Add 1 to evenQ */
evenSum += ch; /*Add the inputted int to evenSum */
}
else
{
oddQ++; /* Add 1 to oddQ */
oddSum += ch; /* Add the inputted int to oddSum */
}
}
printf("Total even integers:\t%d\n"
"Total odd integers:\t%d\n"
"Average even ints:\t%d\n"
"Average odd ints:\t%d\n", evenQ, oddQ, (evenSum/evenQ), (oddSum/oddQ)); /* Print back
the evenQ, oddQ and the averages of even integers and odd integers
*/
return 0;
}
最佳答案
您的问题是由于 getchar
仅拾取字符,而不是整数(如果您输入 1,getchar 将拾取 '1' -char,而不是 int-)。使用 scanf
而不是 getchar
,例如:
#include <stdio.h>
int evenQ = 0, oddQ = 0, evenSum = 0, oddSum = 0; /* We initate variables */
int ch;
int main(void)
{
while ((scanf("%i", &ch) == 1) && (ch != 0 )) /* As long as the input is not 0 keep taking input*/
{
if (ch % 2 == 0) /* If the input is an even integer */
{
evenQ++; /* Add 1 to evenQ */
evenSum += ch; /*Add the inputted int to evenSum */
}
else
{
oddQ++; /* Add 1 to oddQ */
oddSum += ch; /* Add the inputted int to oddSum */
}
}
printf("Total even integers:\t%d\n"
"Total odd integers:\t%d\n"
"Average even ints:\t%d\n"
"Average odd ints:\t%d\n", evenQ, oddQ, (evenSum/evenQ), (oddSum/oddQ)); /* Print back
the evenQ, oddQ and the averages of even integers and odd integers
*/
return 0;
}
其他示例(最糟糕的方式,但更直观):
#include <stdio.h>
int evenQ = 0, oddQ = 0, evenSum = 0, oddSum = 0; /* We initate variables */
int ch = -1;
int main(void)
{
while (ch != 0 ) /* As long as the input is not 0 keep taking input*/
{
scanf("%i", &ch);
if (ch != 0) // Do not take in care int 0
{
if (ch % 2 == 0) /* If the input is an even integer */
{
evenQ++; /* Add 1 to evenQ */
evenSum += ch; /*Add the inputted int to evenSum */
}
else
{
oddQ++; /* Add 1 to oddQ */
oddSum += ch; /* Add the inputted int to oddSum */
}
}
}
printf("Total even integers:\t%d\n"
"Total odd integers:\t%d\n"
"Average even ints:\t%d\n"
"Average odd ints:\t%d\n", evenQ, oddQ, (evenSum/evenQ), (oddSum/oddQ)); /* Print back
the evenQ, oddQ and the averages of even integers and odd integers
*/
return 0;
}
关于c - 我的程序无法正确读取整数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49699313/