[英]Why the place of the assignment of a variable is so important? [C]
在嘗試解決Kochan的練習-C書中的編程(第4循環章節)時,問題是要寫出前10個階乘數。 我試圖用嵌套循環來解決它,但是結果是一個完全的垃圾。 我抬起頭,發現一種解決方案與我的非常相似,但是我注意到變量的位置不同。
先前的解決方案:
/*This program calculates the first 10 factorials*/
#include <stdio.h>
int main(void){
int n,i;
unsigned long int fact=1;
printf(" n\t\t n!\n");
printf("---\t\t--------\n");
for(n=1; n<=10; n++){
for(i = 1; i<=n; i++){
fact*=i;
}
printf("%2d\t\t%7ld\n",n,fact);
}
return 0;
}
輸出:
./factorial
n n!
--- --------
1 1
2 2
3 12
4 288
5 34560
6 24883200
7 857276416
8 -511705088
9 1073741824
10 0
固定解決方案:
/*This program calculates the first 10 factorials*/
#include <stdio.h>
int main(void){
int n,i;
printf(" n\t\t n!\n");
printf("---\t\t--------\n");
for(n=1; n<=10; n++){
unsigned long int fact=1;
for(i = 1; i<=n; i++){
fact*=i;
}
printf("%2d\t\t%7ld\n",n,fact);
}
return 0;
}
輸出:
./factorial
n n!
--- --------
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
注意,唯一的區別是該變量事實在第二個解決方案中是局部的,而在前一個解決方案中是全局的。
所以我想這個問題現在已經澄清了,為什么只改變位置似乎可以解決問題? 為什么存在將變量放在首位的問題? 提前致謝 !
因為在n上的每次迭代期間,變量都被設置為1。如果在迭代n的循環開始時將其設置為1,則可以像在第一個代碼中一樣聲明它。 。
問題不僅僅在於變量的聲明位置和初始化位置 。 在正確的代碼中, fact
對於每個新n
都設置為1
,以便“重新開始”並計算階乘。 在您的代碼中,您無需重置fact
,因此它將繼續保留前n
剩余的值,因此您正在計算n! 乘以先前的結果。
另一種解決方案是刪除內部循環,並利用n ! = n ×( n -1)!。 (這也會表現更好。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.