【问题标题】:Why does my program accept one integer too many and input one too few?为什么我的程序接受一个整数太多而输入一个太少?
【发布时间】:2025-12-15 20:00:02
【问题描述】:

我想了解为什么当我将 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;
}

【问题讨论】:

  • C 数组是从零开始的,这是您的代码的第一个严重问题!您的大小为 2 的数组具有元素 0 和 1,因此在您的情况下,输入的第二个元素将最终出现在数组之外。先更正一下。
  • 我理解你所说的关于数组的内容。你知道程序让我输入超过 2 个元素吗?
  • @RaphaelJones 那是因为你有 \n。因为 scanf() 调用只有在您输入非空白字符时才会完成。
  • @BlueMoon,是的,如果在同一行输入多个数字。如果在每个单独的行中输入额外的数字时读取额外的数字,则需要不同的解释。
  • @JohnBollinger 解释还是一样的。对 scanf 的后续调用接受先前输入的数字。所以它需要一个额外的输入才能完成最后一次 scanf() 调用。

标签: c arrays scanf


【解决方案1】:

你的循环应该是

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

数组索引是基于 C 的 0

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      为什么程序允许我输入 3 个整数

      这个循环恰好运行了 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]);
          }
      

      当它返回数组时,它只返回两个数字

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

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

      【讨论】:

        最近更新 更多