查找数组中的最大元素 - 程序无法识别最后一个元素

Finding max element in array - program won't recognize last element

我写这段小代码只是为了开始学习一些 if 语句和一般的 C 编码。但是,有一个问题。当 运行 时,如果最大的元素是最后一个,代码将无法识别它。这是为什么?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(){
int num[100];
int max;
int i;

    printf("Enter 10 numbers: \n");
    for(i = 1; i < 10; i++){
        scanf("%d\n", &num[i]);
    }
max = num[0];
    for(i = 0; i < 10; i++){

        if(max < num[i]){
            max = num[i];
        }

    }


printf("The biggest nr is: %d", max);


return 0;
}

你的第一个循环应该从 0 开始,而不是 1。

for(i = 0; i < 10; i++){
    scanf("%d\n", &num[i]);
}

max 已经以未初始化的值开始,这里是龙。

内部:

for (i = 1; i < 10; i++) {
    scanf("%d\n", &num[i]);
}

max = num[0];

max 有一个不确定的值,因为循环的计数器变量 i0 开始,而不是 1 ,它给出的结果是数组的第一个元素是' 在循环内部分配。所以你最终将这个不确定的值分配给 max.

要在以下代码中使用不确定值:

if (max < num[i]) {
     max = num[i];
}

调用 undefined behavior.


"However, if I change i=0, the program asks me for 11 inputs before moving on. And among those 11 inputs, the program still won't count the last one, if it is the largest."

"When running it, if the largest element is the last one, the code won't recognize it. Why is that?"

它实际上并没有像您认为的那样要求您为任何 假定的 第 11 个数组元素和循环中的最后一个元素提供第 11 个输入1处理过的数组元素不是你想的那样。那只是给你的印象。

此行为是由 scanf() 调用的格式字符串中的换行符引起的:

scanf("%d\n", &num[i]);

换行符 (\n ) 等于任何白色 space 并且使用此指令,scanf() 读取无限量的白色 space 字符 until 它在输入中找到任何非白色 space 字符以停止使用并且控制流继续到下一个语句。

Why does scanf ask twice for input when there's a newline at the end of the format string?

它不要求输入数组的第 11 个元素(如您所想)。它只需要指令失败的任何非白色 space 字符。

数组的最后一个元素(在循环内部处理1)仍然是第 10 个(num[9]),而不是第 11 个(num[10]) 当您将计数器初始化为 0 并打印时,输出也是正确的:

The biggest nr is: 10

因为10是最后处理的元素num[9]的值。


1) 请注意,您在 num -> int num[100]; 的声明处打错了字。有了这个,你定义了一个包含一百个元素的数组,但实际上你只需要 10 个元素之一 -> int num[10];.


旁注:

  • 同时始终检查 scanf()!

    的 return 值
    if (scanf("%d\n", &num[i]) != 1)
    {
       // Error routine.
    }
    

代码中先后出现两个问题:

  1. 循环应该从 0 开始而不是 1:

    for (int i = 0; i < 10; i++)
    
  2. 主要问题在这里:

    scanf("%d\n", &num[i]);
    _________^^____________
    

    删除 \n,您的问题将得到解决。