C ++不同运行时的不同输出

时间:2020-09-25 03:36:33

标签: c++

我正在运行一个非常简单的C ++代码,以查找5个用户输入的整数中的最大值。该代码有时可以正常运行(通常在使用g ++编译后),有时却无法正常工作。

#include <iostream>
using namespace std;

int main()
{
    int arr[5], max;
    cout<<"Enter the 5 scores: ";
    cin>>arr[0];

    for (int i=1; i<5; i++)
        {
        cin>>arr[i];
        if (arr[i]>max)
            {
            max = arr[i];
            }
        }

    cout<<"Highest score is "<<max<<endl;
    return 0;
}

以下是一些命令行后期。

(base) adam@legion:~/C++$ g++ -pedantic -std=c++11 -Wall max_input.cpp 
(base) adam@legion:~/C++$ ./a.out
Enter the 5 scores: 1 2 3 4 5
Highest score is 5
(base) adam@legion:~/C++$ ./a.out
Enter the 5 scores: 1 2 3 4 5
Highest score is 513655632
(base) adam@legion:~/C++$ 

我不知道怎么了。

1 个答案:

答案 0 :(得分:4)

您尚未初始化max,因此您的程序具有未定义的行为。

在编译器中启用所有警告是一个好主意。如果使用g ++,则为-Wall。这将帮助您检测几种可能导致不确定行为的基本错误。

对于该程序,编译器将很容易就能在分配值之前看到max正在比较中,并且应该发出警告。

最简单的解决方法是假定数组中的第一个值是最大值:

cin >> arr[0];
max = arr[0];

或者,将max初始化为最小可能值。但是,这将无法直接在当前程序中运行,因为您正在读取循环外的第一个值而不进行测试。因此,您的程序会将所有值的读取移入循环。

int max = std::numeric_limits<int>::min();
for (int i = 0; i < 5; i++)
{
    cin >> arr[i];
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
相关问题