c - 为什么我的程序接受的整数太多而输入的整数太少?

标签 c arrays scanf

我想了解为什么当我将 SIZE 定义为 2 时,程序允许我输入 3 个整数。当它返回数组时,它只返回两个数字,而不是我输入的三个数字。感谢您的帮助。

//C How to Program Exercises 2.23
#include <stdio.h>
#include <conio.h>
#define SIZE 2

int main (void){

    int myArray[SIZE];
    int count;
    printf("Please enter 5 integers\n");
    for (count=1;count<=SIZE;count++){
        scanf("%d\n",&myArray[count]);
    }
    for (count=1;count<=SIZE;count++){
        printf("The values of myArray are %d\n",myArray[count]);
    }
    getch();

    return 0;
}

最佳答案

你的循环应该是

for (count=0;count<SIZE;count++)

数组索引是基于 C 的 0

由于 scanf() 调用中有一个空白字符 (\n),因此它会等待您输入非空白字符来完成每个调用。删除 \n:

   for (count=0;count<SIZE;count++){
    scanf("%d",&myArray[count]);
}

关于c - 为什么我的程序接受的整数太多而输入的整数太少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041617/

相关文章:

javascript - 将构造函数传递给 Array.map?

c - 使用 fscanf 从文件中读取

c编程: (scanf and gets)

c - 使用 fscanf (C) 从文件中提取 double

c++ - 如何在 Cygwin 中使用 OpenGL 和 GLUT

c -++p 的定义是什么,其中 p 在 C 中是 const char *p?

android - 解析 JSON 数组时出错

c - 为什么可以将双指针(地址的地址)传递给 scanf?

c - 理解这个 16 位 PRNG

python - 通过冲突从列表中删除