#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Rainfall
{
string month;
double rainfallAmount;
Rainfall(string m)
{
month = m;
}
string getString()
{
string months = month;
return months;
}
double getRainFall()
{
return rainfallAmount;
}
};
void sortRain(Rainfall obj[])
{
double startScan;
double minVal;
int minIndex;
for (int i = 0; i < (12 - 1); i++)
{
minVal = obj[i].rainfallAmount;
minIndex = i;
for (int j = i + 1; j < 12; j++)
{
if (obj[j].rainfallAmount < minVal)
{
minVal = obj[j].rainfallAmount;
minIndex = j;
}
}
obj[minIndex].rainfallAmount = obj[i].rainfallAmount;
obj[i].rainfallAmount = minVal;
}
//int i = 11;
for (int i = 0; i <12; i++)
{
cout << obj[i].month << " " << obj[i].rainfallAmount << endl;
}
}
void inputValues(Rainfall obj[])
{
double rainfallAmount;
for (int i = 0; i < 12; i++)
{
cout << "Enter rainfall for month " << obj[i].month << endl;
cin >> obj[i].rainfallAmount;
}
}
int main()
{
string month1 = "Jan";
string month2 = "Feb";
string month3 = "March";
string month4 = "April";
string month5 = "May";
string month6 = "June";
string month7 = "July";
string month8 = "August";
string month9 = "September";
string month10 = "October";
string month11 = "November";
string month12 = "December";
Rainfall rf[12] = {month1,month2,month3,month4,month5,month6,month7,
month8,month9,month10,month11,month12};
inputValues(rf);
//displayValues(rf);
sortRain(rf);
//displayValues(rf);
}
按照我的任务。“编写一个程序,显示一年中每个月的名称及其降雨量,按降雨量从最低到最高的顺序排列。程序应该使用一个结构数组,每个结构保存一个月的名称和降雨量。使用构造函数设置月份名称。通过调用不同的函数来输入降雨量、对数据进行排序和显示数据,使程序模块化。”。
唯一令人沮丧的错误是,当运行时,月份与数字完全不匹配。我已经试过了所有我能想到的,所以我想我应该在这里发帖。我相信这项任务是要求我按实际数字的顺序发布月份,但它被抵消了。有什么办法解决这个问题或者我看不到的观点吗?
发布于 2020-05-14 08:56:56
您可以重载操作符<以返回较小的雨量值
struct Rainfall
{
bool operator< (const Rainfall& other) const {
return rainfallAmount < other.rainfallAmount;
}
}
现在,您可以将数组与std::排序一起使用。
#include<algorithm>//std::sort is here
inputValues(rf);
std::sort(rf, rf + sizeof(rf)/sizeof(rf[0]));
for (auto r : rf)
{
std::cout << r.month << " " << r.rainfallAmount << std::endl;
}
另外,如果您将变量公之于众,就没有必要为它设置getter,每个人都可以像我一样访问它。
https://stackoverflow.com/questions/61792183
复制相似问题