所以我正在撰寫一個程式來列印 C 中數字的階乘。我的代碼 -
#include <stdio.h>
int main(void)
{
int a,i ;
printf("Enter the number = ");
scanf("%d", &a);
for(i=1; i<a; i )
{
a = a*i;
}
printf("The factorial of the given number is = %d\n",a);
}
現在這個程式正在列印一些垃圾值。我問了一些朋友,他們說要為階乘添加另一個變數并使用帶有該階乘變數的回圈,但是他們都不知道為什么這段代碼是錯誤的。
我的問題是為什么這段代碼是錯誤的?這個 For 回圈在這里做什么,為什么它不列印數字的階乘,而是列印一些垃圾值?
預期產出-
Enter the number = 5
The factorial of the given number is = 120
我得到的輸出是 -
Enter the number = 5
The factorial of the given number is = -1899959296
uj5u.com熱心網友回復:
因為當您增加變數a時,for 回圈條件會發生變化。您i必須小于a,但遞增a將導致條件始終為真。您必須將值保存在另一個變數中,如下所示:
#include <stdio.h>
int main(void)
{
int a, i;
printf("Enter the number = ");
scanf("%d", &a);
int result = a;
for(i=1; i<a; i ){
result = result*i;
}
printf("The factorial of the given number is = %d \n", result);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/473847.html
