代码应该询问用户是否求 1 到 x 的数字之和或求 x 的阶乘。获取用户输入的 x 值后,程序直接结束,不运行 if 和 else if 语句。这是我的代码。
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
任何人都可以向我解释一下我的代码有什么问题以及如何修复它吗?谢谢。
最佳答案
我认为缓冲区有问题。所以,使用
scanf(" %d", &x);
^^^
white-space
而不是
scanf("%d", &x);
并且还使用
scanf(" %c", &choice);
而不是
choice = getchar();
关于c - 程序要求用户输入数字 n,并让用户可以在计算总和和计算 n 的阶乘之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43424040/