繁体   English   中英

如何在一行上打印所有数组项?

[英]How do I print all array items on one line?

我有以下使用数组的代码。 当我运行程序时,它在 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]);
    }
}

程序中的 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]); }

去掉第二个 for 循环中的“\\n”。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM