[英]Factorial of a number in C
所以我正在編寫一個程序來打印 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
我得到的 Output 是-
Enter the number = 5
The factorial of the given number is = -1899959296
因為當您增加變量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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.