如何打印带括号的数组?

问题描述

我正在尝试编写一个要求用户输入数组元素的 C 程序。之后我想将数组打印为 [1,2,3,4]。我的意思是用括号打印出数组,而不仅仅是值。所以,由于我正在努力清楚地理解数组,这就是我尝试的:

#include <stdio.h>

int main() {
        int n,i;
        int num;
        printf("Enter the size of the array:");
        scanf("%d",&n);
        double array[n];
        for (i=0; i<n; ++i){
                printf("Enter the number for position %d: ",i + 1);
                scanf("%i",&num);
        }
}

但我不知道如何用括号打印数组。

解决方法

你可能想要这样的东西:

  for (i = 0; i < n; ++i) {
    printf("Enter the number for position %d: ",i + 1);
    scanf("%i",&array[i]);
  }

  for (i = 0; i < n; ++i) {
    printf("array[%d] = %d\n",i,array[i]);
  }

现在你应该能够自己弄清楚剩下的了。

,

只需存储数字并使用另一个 for 循环打印它们。

#include <stdio.h>

int main() {
  int n,i;
  int num;
  printf("Enter the size of the array:");
  scanf("%d",&n);
  double array[n];
  for (i = 0; i < n; ++i) {
    printf("Enter the number for position %d: ",i + 1);
    scanf("%lf",&array[i]);
  }

  printf("[");
  for (i = 0; i < n; ++i) {
    printf("%s%f",i ? "," : "",array[i]);
  }
  printf("]\n");
  return 0;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...