[英]Calculating factorial multiple times in a loop only works the first time through
這個程序計算n!
僅在第一次通過循環時給出正確的值。 在隨后的每次循環中,它都會給出不正確的值。
我究竟做錯了什么?
#include <stdio.h>
int main()
{
int n,result=1;
while(1){
do{
printf("\nInput n:");
scanf("%d",&n);
}while(n<1);
for (int i=1;i<=n;i++)
{
result*=i;
}
for(int j=1;j<=n;j++)
{
printf("%d",j);
if(j!=n)
{
printf("x");
}
}
printf("=%d",result);
}
}
每次通過外循環都沒有得到相同的result
值的原因是因為在啟動循環時沒有重置它的值。
第一次循環result
從值 1 開始。下一次,它從完成循環的最后一次迭代時的值開始,因為您沒有費心去改變它。
您想在循環開始時將result
設置為 1。
while(1){
result = 1;
do{
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.