2015-09-27 70 views
-3

我有以下使用數組的代碼。當我運行它,它顯示結果9條不同線路9次,但我想顯示的結果只有一次:如何在一行上打印所有數組項目?

#include <stdio.h> 

int main(void) { 

    int sin_num[9]; 
    int num1; 

    for (num1 = 0; num1 < 9; num1++) { 
     printf("Enter your SIN number one by one:"); 
     scanf("%d", &sin_num); 
    } 

    for (num1 = 0; num1 < 9; num1++) { 
     printf("%d \n", &sin_num[num1]); 
    } 
} 
+0

我的意思是由一個線是什麼,我只是想整個數組,只顯示一次,而不是9倍甚至沒有這樣一行這個:數組是123456789 –

+0

刪除'\ n',並在打印數組時從printf語句中移除sin_num [num1]的'&!它應該解決它。 –

+0

刪除\ n仍然會顯示整個陣列9次,我只想要它一次。謝謝 –

回答

3

3問題在你的程序:

  1. 閱讀scanf()手冊頁

    scanf("%d", &sin_num);` 
          ^^^^^^^ here, sin_num is array of int, so scan should take it into its element and not to its base address. 
    

    ,如下圖所示,scanf函數( 「%d」 與指數代替它, & sin_num [i]);

    for (num1 = 0; num1 < 9; num1++) { 
        printf("Enter your SIN number one by one:"); 
        scanf("%d", &sin_num[i]); 
    } 
    
  2. 閱讀printf(3)手冊頁。

    printf("%d \n", &sin_num[num1]); 
          /*  ^, here no need of & as you are looping over array. */ 
          /*  Correction => printf("%d \n", sin_num[num1]); */ 
    
    for (num1 = 0; num1 < 9; num1++) { 
        printf("%d \n", sin_num[num1]); 
    } 
    
  3. 爲了避免多行

    printf("%d \n", sin_num[num1]); 
         /* ^^ as per your requirement, you don't need every element on new line so it should be removed. */ 
    
    for (num1 = 0; num1 < 9; num1++) { 
        printf("%d \n", sin_num[num1]); 
    } 
    
+0

請正確格式化您的答案,以便讀者閱讀它。 –

+0

我在格式化它,同時你格式化了它,再次感謝。 :) –

+0

不要擔心,請嘗試瞭解更多關於降價的信息,以提供高質量的內容和格式答案。 –

0

得到你的第二個for循環擺脫「\ n」個。

for(num1=0; num1<9; num1++) { 
    printf("%d ", sin_num[num1]); 
} 
print("\n");