0
運行此操作時,帶有錯誤註釋的行會導致程序停止工作,至少對我而言。這是如此簡單的代碼,我爲什麼會導致事情破裂而感到困惑?爲什麼此代碼會導致程序停止工作?
#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循環中。
編輯:啊,是的問題是'highIndex,lowIndex = i'。感謝您的幫助
順便說一句,可以考慮使用['標準:: array'(http://en.cppreference.com/w/cpp/container/array)和C++ [隨機數生成器](http://en.cppreference.com/w/cpp/numeric/random)。另外,爲什麼不只是'int length = ARRAY_SIZE;'? –
這是沒有必要編輯你的問題,謝謝。相反,如果答案對您有用(最有用的答案),您應該將其標記爲已接受。 – aslg