计算数组的高值和低值

时间:2010-07-19 19:23:45

标签: c++

 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:在函数'void HL(WeatherStation *)'中:
  chief.cpp:124:错误:初始化时无法将'WeatherStation'转换为'int'   chief.cpp:125:错误:初始化时无法将'WeatherStation'转换为'int'   chief.cpp:128:错误:'*(List +((unsigned int)(((unsigned int)K)* 12u))中的'operator&lt;'不匹配&lt;低”
  chief.cpp:129:错误:在分配中无法将'WeatherStation'转换为'int'   chief.cpp:132:错误:'*(List +((unsigned int)(((unsigned int)K)* 12u))中的'operator&gt;'不匹配)&gt;高”
  chief.cpp:133:错误:无法在分配中将'WeatherStation'转换为'int'

3 个答案:

答案 0 :(得分:0)

它无法将WeatherStation转换为int,因为WeatherStation是一种结构。如果你想获得一个结构的成员,你应该写,例如,List[0].Temperature

答案 1 :(得分:0)

您应该使用C ++容器而不是数组

如果你不喜欢std :: vector,你可以使用std :: array

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;
   } 

另请注意,以命名类型的方式命名变量并不是一个好主意(我的意思是大写)

答案 2 :(得分:0)

你遇到的问题(或者至少是主要问题)就在这里:

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_elementstd::max_element