c++嵌套循环
C++ nested loops
我必须编写一个程序,向用户询问年数,然后向用户询问这些年中每个月以毫米为单位的降雨量。我必须计算总月份数、总降雨量英寸数、每月平均降雨量、计算所有月份的最大降雨量,并输出降雨量最大的月份名称(将月份数字转换为名称)和年份。到目前为止,我已经编写了这段代码,但是我不知道如何准确地输出确切的月份名称和降雨量最高的年份,即使我已经计算出降雨量最高的值。
const int numMonths = 12;
int numYears, months, largest = 0;
double sum = 0;
cout << "Please enter the number of years: ";
cin >> numYears;
cin.ignore();
for (int years = 1; years <= numYears; years ++)
{
for (int months = 1; months <= numMonths; months ++)
{
double rain;
cout << "Please enter the rainfall in mm for year " << years << ", month " << months << "n";
cin >> rain;
sum += rain;
if (rain > largest){
largest = rain;
}
cin.ignore();
}
}
int totalMonth = numYears*numMonths;
double avgRain = sum / totalMonth;
cout << "Total number of months: " << totalMonth << "n";
cout << "Total inches of rainfall for the entire period: "<< sum << "n";
cout << "Average rainfall per month for the entire period: " << avgRain << "n";
cout << "Highest rainfall was " << largest << ;
cin.get();
return 0;
不如这样写:
if (rain > largest_rain){
largest_rain = rain;
largest_month = months;
largest_year = years;
}
要将月数映射到名称,我将它们放在字符串数组中。
string[] months = {"January","February","March"...};
然后取月数(如果是1索引则减去1)并将该索引打印到数组中。
所以它们合起来是这样的
string [] month = {"January","February", "March"/*Fill in the rest of the months*/};
int largestMonthIndex = largest_month-1;
cout << "Month that the largest rain fall occurred in: " <<month[largetMonthIndex];
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 毕达哥拉斯三重嵌套循环误解
- T(n) 表示嵌套循环
- 2 个嵌套循环的时间复杂度
- 嵌套循环背后的逻辑
- 使用 %s C++嵌套循环
- 嵌套循环和重复迭代器
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- C++在乘法图中放置随机值(嵌套循环)
- 如何使用 OpenMP 减少嵌套循环?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 学习嵌套循环C++与示例混淆
- 如何在CUDA中嵌套循环
- std::vector上的嵌套循环
- 具有动态数组分配的OpenMP嵌套循环
- 两个嵌套循环的运行时间复杂性:二次型还是线性