2016-12-24 19 views
0

我正試圖運行下面的代碼,同時使用調試器。在下面的循環「for (i=0;i<n;i++) pin[i]=0;」結束時,n的值會從我給出的值變爲0並且變爲0.我不明白爲什麼會發生這種情況,所以對於它發生的原因的幫助將不勝感激。哦,還有一件事。如果我忽略它,並且只要我給出n個值,我將該值賦給另一個整數,以便在n變成0時能夠使用它,我的程序崩潰了。例如,當你使用一個你沒有賦值的變量時,它就是你所得到的類型的崩潰。整數的值從不知所云

main() 
{ 
    int i,j,k,n,pin[n]; 
    printf("Give the size of the array:\n"); 
    scanf("%d", &n); 
    do{ 
     printf("Give the number of the iterations:\n"); 
     scanf("%d", &k); 
    }while (k<1||k>n); 
    for (i=0;i<n;i++) 
     pin[i]=0; 
    for (j=0;j<k;j++){ 
     for (i=0;i<n;i++){ 
      if (i%j==0){ 
       if (pin[i]==0) 
        pin[i]=1; 
       else 
        pin[i]=0; 
      } 
     } 
    } 
    for (i=0;i<n;i++) 
     printf("%d ", pin[i]); 
} 
+1

您的代碼具有未定義行爲,因爲'當你定義'銷[N]'N'是未初始化。進一步向下移動'pin'的定義,越過輸入和驗證'n'的循環。 –

+1

你的頭銜顯示你遇到了未定義的行爲。你一直困惑的是,機器會隨機完成某件事,你從來沒有告訴過它。不幸的是,這主要是由於你想要做什麼和你做什麼之間的差異造成的。調試器幫助你分析後者,直到它符合前者。祝大家聖誕快樂。 –

+0

Yeap,就是這樣,非常感謝你! – Achilles

回答

1

你不能除以0和定義pin[n]其中n被初始化。

#include <stdio.h> 

int main() { 
    int i, j, k, n; 
    printf("Give the size of the array:\n"); 
    scanf("%d", &n); 
    int pin[n]; 
    do { 
     printf("Give the number of the iterations:\n"); 
     scanf("%d", &k); 
    } while (k < 1 || k > n); 
    for (i = 0; i < n; i++) 
     pin[i] = 0; 
    for (j = 0; j < k; j++) { 
     for (i = 0; i < n; i++) { 
      if (j != 0 && i % j == 0) { 
       if (pin[i] == 0) 
        pin[i] = 1; 
       else 
        pin[i] = 0; 
      } 
     } 
    } 
    for (i = 0; i < n; i++) 
     printf("%d ", pin[i]); 
} 

測試

Give the size of the array: 
3 
Give the number of the iterations: 
2 
1 1 1 

測試2

Give the size of the array: 
5 
Give the number of the iterations: 
4 
1 1 0 0 0 
+0

非常感謝您的建議!代碼現在運行順利! – Achilles

相關問題