为什么以下代码在阵列中显示上个月的最后一个月,而不是显示降雨量最高和最低降雨量的月份
Why does the following code shows the last month in the array instead of showing the months with the highest and the lowest rainfall?
我有一个分配,我需要在每个月的降雨量中获取用户输入。最后,我需要平均降雨以及显示最高和最低降雨的月份(使用当月的名称(。除了显示最低和最高月份外,一切都可以使用。由于某种原因,我的代码总是显示12月,而不是实际的最低和最高月份。最低月=月份[count];和最高月份=月份[countup];我怀疑的代码行是引起一些问题。感谢社区可以提供的任何帮助。
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
const int SIZE = 12;
double RAINFALL[SIZE];
string MONTHS[SIZE] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for (int counter = 0; counter < SIZE; counter++)
{
cout << "Please enter rainfall for " << MONTHS[counter] << ": ";
cin >> RAINFALL[counter];
while (RAINFALL[counter] < 0.00) // Input validation to prevent neg amounts being entered
{
cout << "Invalid Data (negative rainfall)!" << endl;
cout << "Please re-enter rainfall for " << MONTHS[counter] << ": ";
cin >> RAINFALL[counter];
}
}
int tnum;
double average, sum = 0;
for (tnum = 0; tnum < SIZE; tnum++)
sum += RAINFALL[tnum];
average = sum / SIZE;
cout << "Average rainfall = " << average << endl;
int count;
int lowest;
string lowestMonth = MONTHS[0];
lowest = RAINFALL[0];
for (count = 1; count < SIZE; count++)
{
if (RAINFALL[count] < lowest)
lowest = RAINFALL[count];
lowestMonth = MONTHS[count];
}
cout << "Lowest rainfall in " << lowestMonth << " of: " << lowest << endl;
int countup;
int highest;
string highestMonth = MONTHS[0];
highest = RAINFALL[0];
for (countup = 1; countup < SIZE; countup++)
{
if (RAINFALL[countup] > highest)
highest = RAINFALL[countup];
highestMonth = MONTHS[countup];
}
cout << "Highest rainfall in " << highestMonth << " of: " << highest << endl;
return 0;
}
您在if-Statement中缺少一个括号,因此仅执行第一行。
for (count = 1; count < SIZE; count++)
{
if (RAINFALL[count] < lowest) { // <-- BRACKET
lowest = RAINFALL[count];
lowestMonth = MONTHS[count];
} // <-- BRACKET
}
当然,还有更多模块化的方法:
std::string lowest_month = MONTHS[
std::min_element(&RAINFALL[0], &RAINFALL[SIZE]) - &RAINFALL[0]
];
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- 为什么以下代码在阵列中显示上个月的最后一个月,而不是显示降雨量最高和最低降雨量的月份