在C++中显示最高和最低数字
Displaying Hjighest and Lowest number in C++
我正在尝试这种方式。似乎更加简化了。现在只是想知道如何包括月份名称,并让程序输出降雨量最大的月份的名称,而不是用户输入的数字。
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int a[12];
int x;
for (x=0; x<12; x++)
{
cout << "Insert days of rainfall for month "<<x+1<<endl;
cin >>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<12)
{
if (a[e]>max)
{
max = a[e];
}
else if (a[e]<min)
{
min = a[e];
}
e++;
cout<<"The rainiest month was " <<max<<endl;
cout<<"The least rainy month was " <<min<<endl;
getch ();
return 0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
您的average
计算有点偏离,在数学方面必须考虑运算顺序。乘法和除法总是先做,然后是加法和减法。你最终得到的结果是,只有dec
除以12,然后你把所有其他的日子都加进去。要解决这个问题,你需要把所有月份的加法都用括号括起来,迫使加法先发生,然后再除法。在这种情况下,您可以只使用year
变量,因为它已经是所有月份加在一起并除以12。
就您的问题而言,您希望显示输入的最高值和最低值,但我看不到有任何尝试在您的代码中解决此问题。我不太愿意只为你写代码,所以我只简单解释一下你需要做什么。查看每个月的值,每次查看下一个月时,都会将其与您记忆中的当前最高值和当前最低值进行比较。当新的月份有一个新的更高或更低的值时,您将替换您记忆中的值。一旦你每个月都循环,你就会得到最高和最低的价值。
最快、最干净的方法是使用std::vector
这样的容器。然后使用std::sort
对其进行排序。
// Our container
std::vector<double> userInput;
// Populate the vector. Please don't cin into a double!
// Sort it.
std::sort (userInput.begin(), userInput.end());
// The highest value will be the last value in the vector
// whilst the lowest value will be the first one
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在 txt 文件中显示前两个数字的程序
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么 sf::Text 显示点而不是数字?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 未来值公式显示疯狂巨大数字的输出
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 无法在C++中显示反转的数字
- 如何执行此程序,将键入的数字显示为数字值的多次
- Cpp代码故障(显示意外数字)
- 如何让我的代码显示文件名不正确或文件中数字的平均值?
- 为什么C++显示错误的数字?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- C++编译器只显示数字,不显示正确的输出
- 输入的数字与代码显示的数字不同,在结构中使用数组,为什么?
- 如何计算和显示C++中5个数字的平均值?
- 以8位数字形式输入日期并以英文形式显示
- 为什么我的 rand() 数字显示为 0