为什么这段代码会导致程序停止工作?
Why does this code cause the program to stop working?
当您 运行 执行此操作时,带有错误注释的行会导致程序停止工作,至少对我而言是这样。这是如此简单的代码,我有点困惑为什么这会导致事情崩溃?
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int ARRAY_SIZE = 100;
bool runAgain ( ) {
char runChar;
cout << "\n\nRun again? (Y/N)";
cin >> runChar;
runChar = toupper(runChar);
if(runChar != 'Y')
return false;
system("cls");
return true;
}
int main ( ) {
int nums[ARRAY_SIZE];
int length;
int num, highIndex, lowIndex;
length = sizeof(nums)/sizeof(int);
srand((unsigned)time(NULL)); //make numbers more random
do {
cout << "Array contains: \n";
for(int i = 0; i < length; i++) {
num = rand() % 1000 + 1;
if(i == 0)
highIndex, lowIndex = i;
else if(num > nums[highIndex]) //@@ ERROR occurs on this line
highIndex = i;
else if(num < nums[lowIndex])
lowIndex = i;
nums[i] = num;
cout << num << "\n";
}
cout << "\nHighest Value: " << nums[highIndex] << " at index " << highIndex;
cout << "\nLowest Value: " << nums[lowIndex] << " at index " << lowIndex;
}while(runAgain());
return 0;
}
错误具体是 windows 说 .cpp 已停止工作并表面上结束了 运行。从 运行 调试器中,我知道它发生在循环的第一次迭代之后,在 for 循环中的第一个 else if 中。
编辑:啊,是的,问题是 'highIndex, lowIndex = i'。感谢帮助
问题是highIndex, lowIndex = i;
。
这并不像您想象的那样,将 highIndex
和 lowIndex
赋给 i
的值。仅分配 lowIndex
,highIndex
保持未初始化状态。因此,当您尝试使用 highIndex
取消引用数组时,程序会崩溃,因为值可以是任何值。
将您的代码行更改为:
highIndex = lowIndex = i;
当您 运行 执行此操作时,带有错误注释的行会导致程序停止工作,至少对我而言是这样。这是如此简单的代码,我有点困惑为什么这会导致事情崩溃?
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int ARRAY_SIZE = 100;
bool runAgain ( ) {
char runChar;
cout << "\n\nRun again? (Y/N)";
cin >> runChar;
runChar = toupper(runChar);
if(runChar != 'Y')
return false;
system("cls");
return true;
}
int main ( ) {
int nums[ARRAY_SIZE];
int length;
int num, highIndex, lowIndex;
length = sizeof(nums)/sizeof(int);
srand((unsigned)time(NULL)); //make numbers more random
do {
cout << "Array contains: \n";
for(int i = 0; i < length; i++) {
num = rand() % 1000 + 1;
if(i == 0)
highIndex, lowIndex = i;
else if(num > nums[highIndex]) //@@ ERROR occurs on this line
highIndex = i;
else if(num < nums[lowIndex])
lowIndex = i;
nums[i] = num;
cout << num << "\n";
}
cout << "\nHighest Value: " << nums[highIndex] << " at index " << highIndex;
cout << "\nLowest Value: " << nums[lowIndex] << " at index " << lowIndex;
}while(runAgain());
return 0;
}
错误具体是 windows 说 .cpp 已停止工作并表面上结束了 运行。从 运行 调试器中,我知道它发生在循环的第一次迭代之后,在 for 循环中的第一个 else if 中。
编辑:啊,是的,问题是 'highIndex, lowIndex = i'。感谢帮助
问题是highIndex, lowIndex = i;
。
这并不像您想象的那样,将 highIndex
和 lowIndex
赋给 i
的值。仅分配 lowIndex
,highIndex
保持未初始化状态。因此,当您尝试使用 highIndex
取消引用数组时,程序会崩溃,因为值可以是任何值。
将您的代码行更改为:
highIndex = lowIndex = i;