基本上问题是findLowest函数没有按照我的计划做它。我知道这是一个逻辑错误,但我似乎无法找出变量没有更新的原因。它们总是默认使用它们实例化的值。
#include <stdafx.h>
#include <string>
#include <iostream>
using namespace std;
//Function prototypes
void findLowest(int regAccidents[], int arraySize, string regNames[]);
int getNumAccidents(string);
const int NUM_REGIONS = 5;
int main(){
string regionNames[NUM_REGIONS] = { "North", "South", "East", "West", "Central" };
int regionAccidents[NUM_REGIONS];
for (int i = 0; i < NUM_REGIONS; i++){//Populates the accident array
regionAccidents[i] = getNumAccidents(regionNames[i]);
if (regionAccidents[i] < 0)//checks to see if there are any accidents counts lower than 0
regionAccidents[i] = 0;
}
findLowest(regionAccidents, NUM_REGIONS, regionNames);
}
int getNumAccidents(string region){//returns the accidents for a specific region to be assigned to the regionAccidents[] array in main()
int regionAccidents = 0;
cout << "How many accidents for " << region << "? ";
cin >> regionAccidents;
return regionAccidents;
}
void findLowest(int regAccidents[], int arraySize, string regNames[]){ //used to determine what the lowest number of accidents is
int lowest = regAccidents[0]; //once that is found, update the lowRegion string of the accident location
string lowRegion = regNames[0];
for (int i = 0; i < arraySize; i++){
if (regAccidents[i] < regAccidents[i++]){
lowest = regAccidents[i];
lowRegion = regNames[i];
}
}
cout << "The region with the lowest amount of accidents is: " << lowRegion << endl;
cout << "The lowest number of accidents is: " << lowest << endl;
}
答案 0 :(得分:1)
if (regAccidents[i] < regAccidents[i++]) { ...
是错误的,您需要将当前索引与目前为止找到的最低值进行比较:
if (regAccidents[i] < lowest) { ...
表达式regAccidents[i] < regAccidents[i++]
将从不为真,因为您正在比较数组中的相同项目。然而,当你最不期望它时,会增加i
。这并不重要,因为这是你的主要问题完全隐藏的次要问题: - )
答案 1 :(得分:0)
是的,您的代码中存在逻辑错误。 findLowest应如下所示:
int lowest = regAccidents[0];
string lowRegion = regNames[0];
for (int i = 1; i < arraySize; i++){
//^^you have initialized lowest as regAccidents[0], so search from 1
if (regAccidents[i] < lowest ){
//^^if current is smaller than lowest, update lowest and name
lowest = regAccidents[i];
lowRegion = regNames[i];
}
}
答案 2 :(得分:0)
你确实对现在输出的内容说了什么。 你用这条线的增量超越了数组吗?
if(regAccidents [i]&lt; regAccidents [i ++])