我尝试创建一个允许用户输入10个值的程序,然后在数组中显示最高值。每次我运行程序时,它都会给出一个错误,说堆栈已损坏。请帮忙?这是我的代码:
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int number[SIZE];
int count;
int highest;
for (count = 0; count < SIZE; count++)
{
cout << "Enter 10 numbers" << endl;
cin >> number[SIZE];
}
for (count =1; count < SIZE; count++)
{
if (number[count] > highest)
highest = number[count];
}
cout << highest << endl;
return 0;
}
答案 0 :(得分:2)
首先
cin >> number[SIZE];
- &gt; std::cin >> number[count];
其次highest
未初始化。将number[0]
初始化为
highest = number[0]; /* first time it should have array 0th element value */
for (count =1; count < SIZE; count++) {
if (number[count] > highest)
highest = number[count];
}
答案 1 :(得分:1)
cin >> number[SIZE];
应该是
cin >> number[count];
看起来你在这里写错了。你现在实际做的是将10个数字读入阵列的同一个位置。该位置是您拥有的数组的最后一个索引之后的位置,从而导致未定义的行为。对你而言,这表现为一个损坏的堆栈。&#34;
答案 2 :(得分:1)
你犯了一些错误。这将是您的代码的更正版本:
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int number[SIZE];
int count;
int highest;
for (count = 0; count < SIZE; count++)
{
cout << "Enter 10 numbers" << endl;
cin >> number[count];
cout << "you entered: " << number[count] << endl;
}
highest = number[0];
for (count = 1; count < SIZE; count++)
{
if (number[count] > highest)
highest = number[count];
}
cout << highest << endl;
return 0;
}
但请考虑以下解决方案,如果您开始学习stl,则可以简化和改进代码。
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::cout << "Enter 10 numbers:\n";
const int size = 10;
std::vector<int> v(size);
for (auto& val : v) std::cin >> val;
std::cout << "max: " << *std::max_element(v.begin(),v.end()) << "\n";
}