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

Why does my program accept one integer too many and input one too few?

我想了解为什么当我将 SIZE 定义为 2 时程序允许我输入 3 个整数。当它 returns 数组时它只有 returns 两个数字而不是三个我有 entered.Thanks 需要你的帮助。

//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++)

数组索引 0 基于 C。

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

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

C 数组的索引从 0 开始,而不是从 1 开始。 C 不会自动对数组访问执行边界检查,事实上,您的代码格式正确。但是,它的 运行time 行为是 undefined,因为它使用数组元素表达式在该数组的边界之外写入,另外,由于它使用要在该数组边界之外读取的数组元素表达式。

因为程序肯定在每个 运行 上都表现出未定义的行为,所以绝对不能说它应该做什么。如果在实践中您观察到输入循环迭代三次,那么可能的解释是第二次迭代覆盖了 count 变量的值。考虑到声明变量的顺序,这是未定义行为的合理表现。

另一方面,输出循环会精确地迭代您告诉它执行的次数:一次 count == 1,再一次 count == 2。鉴于程序执行的一般不确定性,这绝不是保证,但这是我能想到的最不令人惊讶的行为。

why the program allows me to input 3 integers

这个循环恰好运行了 2 次:

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

但是当您在 scanf() 中使用 \n 时,这个 scanf() 会一直等到您输入任何空格。

Proper Input code:

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

And when it returns the array it only returns two numbers

您的原始输出代码正确打印了第一个数字,但您的第二个数字是垃圾值。

Proper Output Code:

for (count=0;count<SIZE;count++){
        printf("The values of myArray are %d\n",myArray[count]);
    }

所以完整代码是这样的:

//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=0;count<SIZE;count++){
        scanf("%d",&myArray[count]);
    }
    for (count=0;count<SIZE;count++){
        printf("The values of myArray are %d\n",myArray[count]);
    }
    getch();

    return 0;
}