printf("number to input: \n");
scanf("%d",&y);
for(x=0;x<y;x++){
scanf("%d",&num);
}
printf("Numbers entered: %d \n",num);
假设我们输入了值 4 。 scanf 将循环 4 次并为每个循环输入一个值 1,2,3,4
最终输出应该显示1 2 3 4
有什么想法吗?
最佳答案
您应该使用数组来存储值。 您将不得不进行动态分配,因为数据的数量会发生变化,并且可以在读取数据之前由用户输入来确定。
这是一个示例实现:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x,y=-1;
int *num;
printf("number to input: \n");
scanf("%d",&y);
if(y<0)return 1;
num = malloc(sizeof(int)*y);
if(num==NULL)return 1;
for(x=0;x<y;x++){
scanf("%d",&num[x]);
}
printf("Numbers entered: ");
for(x=0;x<y;x++){
printf("%d ",num[x]);
}
printf("\n");
free(num);
return 0;
}
关于c - 如何在循环中读取多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458716/