计算阵列的高值和低值
struct WeatherStation {
string Name;
double Temperature;
};
void Initialize(WeatherStation[]);
void HL(WeatherStation List[]);
int main()
{
string Command;
WeatherStation Stations[5];
//some commands
}
void Initialize(WeatherStation StationList[])
{
StationList[0].Name = "A";
StationList[0].Temperature = 0.0;
StationList[1].Name = "B";
StationList[1].Temperature = 0.0;
StationList[2].Name = "C";
StationList[2].Temperature = 0.0;
StationList[3].Name = "D";
StationList[3].Temperature = 0.0;
StationList[4].Name = "E";
StationList[4].Temperature = 0.0;
}
void HL(WeatherStation List[])
{
int K;
int Low = List[0];
int High = List[0];
for(K = 0 ; K < 5 ; K++)
if(List[K] < Low)
Low = List[K];
for(K=0 ; K < 5 ; K++)
if(List[K] > High)
High = List[K];
cout << "Lowest Temperature: " <<Low << endl;
cout << "Highest Temperature: "<< High << endl;
}
最后一部分让我绊倒。计算阵列的高值和低值
chief.cpp: In function ‘void HL(WeatherStation*)’:
chief.cpp:124: error: cannot convert ‘WeatherStation’ to ‘int’ in initialization
chief.cpp:125: error: cannot convert ‘WeatherStation’ to ‘int’ in initialization
chief.cpp:128: error: no match for ‘operator<’ in ‘*(List + ((unsigned int)(((unsigned int)K) * 12u))) < Low’
chief.cpp:129: error: cannot convert ‘WeatherStation’ to ‘int’ in assignment
chief.cpp:132: error: no match for ‘operator>’ in ‘*(List + ((unsigned int)(((unsigned int)K) * 12u))) > High’
chief.cpp:133: error: cannot convert ‘WeatherStation’ to ‘int’ in assignment
它不能转换WeatherStation
到int
因为WeatherStation
是一个结构。如果你想获得一个结构的成员,你应该写,例如,List[0].Temperature
。
您应该使用C++容器代替阵列
如果你不喜欢的std ::向量,就可以使用std ::阵列
void Initialize(std::vector<WeatherStation>&);
void HL(const std::vector<WeatherStation>&);
int main()
{
string Command;
std::vector<WeatherStation> Stations;
//some commands
}
void Initialize(std::vector<WeatherStation>& StationsList)
{
StationList.push_back({"A", 0.0});
StationList.push_back({"B", 0.0});
StationList.push_back({"C", 0.0});
StationList.push_back({"D", 0.0});
StationList.push_back({"E", 0.0});
}
void HL(const std::vector<WeatherStation>& List)
{
cout << "Lowest Temperature: " << std::min_element(List.begin(), List.end())->Temperature << endl;
cout << "Highest Temperature: "<< std::max_element(List.begin(), List.end())->Temperature << endl;
}
另外请注意,这不是一个很好的主意因为你的名字你的类型来命名你的变量以同样的方式(我的意思是大写)
您遇到的问题(或者至少主要的问题)就在这里:
if(List[K] < Low)
Low = List[K];
if(List[K] > High)
High = List[K];
List
被定义为WeatherStation
结构的数组。你想要的东西,如:
if (list[K].Temperature < Low)
Low = List[K].Temperature;
编辑:您可能还需要考虑使用std::min_element
和std::max_element
代替。
温度是双重的,所以双低=等等。 – 2010-07-19 19:29:59
必须使用* epsilon *因子,而不是与双等同。双打很少完全相同。 – 2010-07-19 19:32:13
可能'WeatherStation :: Temperature'应该是另一端的'int'。 – 2010-07-19 19:34:23