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

MNK*_*MNK 1 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;
}
Run Code Online (Sandbox Code Playgroud)

以下是一些命令行扩展。

(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++$ 
Run Code Online (Sandbox Code Playgroud)

我不知道出了什么问题。

pad*_*ddy 5

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

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

对于这个程序,编译器max在被赋值之前很容易就能看到它正在比较中使用,它应该发出警告。

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

cin >> arr[0];
max = arr[0];
Run Code Online (Sandbox Code Playgroud)

或者,初始化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];
    }
}
Run Code Online (Sandbox Code Playgroud)