我刚刚制作了一个计算int-interval中整数阶乘的程序。我还插入了一个while循环,因此它会一直运行。
但是我因为这个循环而遇到了问题:例如,如果我第一次输入数字5,我得到输出120,这是好的,因为5!= 120。但是第二次输入5时,我得到了一个完全相同的数字(在2.尝试时,所有数字都是相同的情况)。我认为这是因为我的计划一直在保存“因子”的价值。或循环计数器' c'。
所以我基本上需要在每次计算阶乘后重置两个变量,但我不知道要重置这个变量!
这是我的代码:
int main(void) {
uart_init(); // open the communication to the microcontroller
io_redirect(); // redirect input and output to the uart
int number;
int c;
int factorial=1;
while(1){
printf("Please enter an integer to calculate its factorial:\n");
scanf("%d", &number); //Our input number is stored in the variable 'number'
for (c=1; c<=number;++c) //The variable 'c' is incremented by 1, until it equals 'number' (input)
factorial=factorial*c; //Every time 'c' is incremented by 1, it is multiplied with 'factorial' which initially is 1.
printf("Factorial of %d is %d\n\n\n", number, factorial); //The factorial is printed.
}
return(0);
}
答案 0 :(得分:1)
添加
factorial = 1;
在while循环结束时。
答案 1 :(得分:1)
您需要在循环内重置factorial
。
答案 2 :(得分:1)
您重新使用factorial而不重新初始化它。您需要在while循环开始时将其设置为1。
答案 3 :(得分:0)
放
int factorial=1;
在while
循环内。
while(1){
// Reset factorial by 1
int factorial=1;
printf("Please enter an integer to calculate its factorial:\n");
scanf("%d", &number);
for (c=1; c<=number;++c)
factorial = factorial*c;
printf("Factorial of %d is %d\n\n\n", number, factorial);
}
答案 4 :(得分:0)
在while循环中添加factorial = 1
,因此while循环的主体如下所示:
while(1){
printf("Please enter an integer to calculate its factorial:\n");
scanf("%d", &number); //Our input number is stored in the variable 'number'
for (c=1; c<=number;++c) //The variable 'c' is incremented by 1, until it equals 'number' (input)
factorial=factorial*c; //Every time 'c' is incremented by 1, it is multiplied with 'factorial' which initially is 1.
printf("Factorial of %d is %d\n\n\n", number, factorial); //The factorial is printed.
factorial = 1;
}