while 循环从标准输入读取整数值

While loop to read interger values from standard input

我需要我的程序将整数值读入数组中的相邻元素,并将计数器设置为读取的整数总数。我还需要另一个循环来将值打印到屏幕上。

我该怎么做?

#include <stdio.h>

int main(void) {
    int numArray[100];
    int counter, value;

    printf("Enter array length \n");
    scanf("%d", &counter); 

    int i = 0;
    while(i < counter) {
        scanf("%d", &numArray[i]);
        value = numArray[i];
        i++;
    }

    return 0;
}

I need my program to read integer values into adjacent elements in the array, and set the counter to the total number of integers read. I also need another loop to print the values to the screen.

How do I go about doing this?

整个程序应该可以运行,但是您需要初始化:

value = 0; /*Initialize Variables */
counter = 0;

在 C 语言中,当您输入一个函数时,如 value 和 counter 等主要变量会使用随机值进行初始化——如果您不进行初始化。这可能会给您带来麻烦。

 while(i < counter) /*Scans the values into the array */
 {
   scanf("%d", &numArray[i]);
   value = numArray[i];
   i++;
 }

这里的scanf函数扫描你输入到数组中的值。 我不确定你会用 values 做什么;您的数组为您存储值。但是,如果您以不同的方式使用它,它可能会使您的代码更短。

打印值的循环看起来与您的原始循环相似。

while(i < counter)
{
  printf("%d", &numArray[i]); /*Prints the values in the array */
  i++;
}