2015-09-27 73 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");