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

时间:2015-03-25 18:08:25

标签: c arrays function loops scanf

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

我该怎么做?

#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;
}

1 个答案:

答案 0 :(得分:0)

  

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

     

我该怎么做?

整个程序应该有效,但是你需要初始化:

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

在C中,当您输入类似主要变量的函数时,如值和计数器将使用随机值初始化 - 如果您不进行初始化。这可能会给你带来麻烦。

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

此处的scanf函数会扫描您输入数组的值。 我不确定你会使用什么价值;您的数组为您存储值。但是,如果您以不同的方式使用它,它可能会缩短您的代码。

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

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