gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:47:42 24 4
gpt4 key购买 nike

我正在运行一个非常简单的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++$
我不知道怎么了。

最佳答案

您尚未初始化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];
}
}

关于c++ - C++不同运行时的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64057436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com