我正在从stroustrups书中进行练习。钻取要求您每次通过循环读取一个double并使用2个变量来跟踪到目前为止读取的最小值和最大值。这是我的尝试,但目前它的效果不是很好。任何帮助将不胜感激。
#include <iostream>
using std::cout;
using std::cin;
int main()
{
double d = 0;
double smallest = 0;
double largest = 0;
while (cin >> d)
{
if (d > largest)
{
largest = d;
cout << largest << " is the largest value yet"
<< '\n';
}
else if (d < largest)
{
smallest = d;
cout << smallest << " is the smallest value yet"
<< '\n';
}
else
continue;
}
}
答案 0 :(得分:3)
看起来你的问题是你有0作为最低起点。这是你可能拥有的最低限度。将其设置为可能的最大双精度值。这样的事情对你有用。
我也删除了你的其他人,因为你的第一个号码应该是最大和最小的,对吗?
您的largest
if语句中也有smallest
。
#include <iostream>
using namespace std;
int main()
{
double d = 0;
double smallest = DBL_MAX;
double largest = -DBL_MAX;
while (cin >> d)
{
if (d > largest)
{
largest = d;
cout << largest << " is the largest value yet\n\r";
}
if (d < smallest)
{
smallest = d;
cout << smallest << " is the smallest value yet\n\r";
}
}
}
如果你想把你的其他人留在那里,解决方案几乎是一样的,但我们基本上只是隐藏第一遍将两者都设置为相同的值。这对我来说没有意义,但在这里你有它。这是您使用1,71,41示例解决问题的方法,其中41设置为代码中的最小数字。这是不正确的,因为它没有将1设置为最小和最大。
#include <iostream>
using namespace std;
int main()
{
double d = 0;
double smallest = DBL_MAX;
double largest = -DBL_MAX;
bool firstPass = true;
while (cin >> d)
{
if (d > largest)
{
largest = d;
cout << largest << " is the largest value yet\n\r";
}
else if (d < smallest)
{
smallest = d;
cout << smallest << " is the smallest value yet\n\r";
}
if(firstPass)
{
firstPass = false;
smallest = d;
}
}
}
答案 1 :(得分:-2)
else if (d < largest)
应该是
else if (d < smallest)
和
double smallest = 0;
应该是
double smallest = 1000000; // or some very large number