當我在 for 回圈內外初始化變數時,我嘗試了一種回溯演算法并收到不同的結果,但我不明白為什么。
#include <stdio.h>
int a[10];
int n;
int i;
int j; //difference
void display(){
for (i = 1; i <= n; i ) printf("%d", a[i]);
printf("%\n");
}
void Try(int k){
for (j = 0; j <= 1; j ){ //difference
a[k] = j;
if (k == n) display();
else Try(k 1);
}
}
int main(){
n = 2;
Try(1);
}
和
#include <stdio.h>
int a[10];
int n;
int i;
//int j; //difference
void display(){
for (i = 1; i <= n; i ) printf("%d", a[i]);
printf("%\n");
}
void Try(int k){
for (int j = 0; j <= 1; j ){ //difference
a[k] = j;
if (k == n) display();
else Try(k 1);
}
}
int main(){
n = 2;
Try(1);
}
第一個代碼的結果只是 00, 01 但第二個代碼的結果是 00, 01, 10, 11(預期結果)。
為什么會有這種區別?
uj5u.com熱心網友回復:
在第一種情況下:
j是一個全域變數,所以當 execute else Try(k 1);j 被重新初始化為零和之后并退出現在等于 2Try(k 1);的值時j,所以它將存在 for 回圈并結束您的代碼。
但在第二種情況下:
j是一個區域變數,所以當try 再次進入函式時,它被j視為與舊的不同的變數j。它與您嘗試訪問的變數不同。
撰寫遞回函式時要小心。避免全域變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341531.html
