所以我对编程非常陌生。我正在尝试创建一个程序,用于计算流经管道的液体的雷诺数。赋值要求我使用"if“语句来根据用户在提示时输入的温度来确定液体的实际粘度。但是,只有最后一个"if“语句才能计算出正确的值。所有的"if“语句都具有相同的结构,但只有最后一条语句有效。请帮帮忙。
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double Rnumber, Velocity, viscosity, diameter, temp;
cout << "Enter the temperature of the liquid (degrees Celsuis): " << endl;
cin >> temp;
if (temp == 5.0)
{
viscosity = (1.49 * pow(10, -6));
}
if (temp == 10.0)
{
viscosity = (1.31 * pow(10, -6));
}
if (temp == 15.0)
{
viscosity = (1.15 * pow(10, -6));
}
cout << "Enter the velocity of the liquid (m/s): " << endl;
cin >> Velocity;
cout << "Enter the diameter of the pipe (m): " << endl;
cin >> diameter;
Rnumber = ((Velocity * diameter) / (viscosity));
cout << "The Reynolds number for the system is " << Rnumber << " ."<< endl;
cin.ignore(2);
return 0;
}发布于 2018-06-20 06:53:14
你不应该比较浮点数是否相等。
在您的例子中,这可能是比较的技巧:
bool floatEqual(double a, double b)
{
const double epsilon = 0.001;
return ((a + epsilon) > b) && ((a - epsilon) < b);
}但总的来说,这是而不是一个好的方法(参见http://floating-point-gui.de/errors/comparison/)
你的程序应该能处理任何给定值,例如5.1度。您可能希望将粘度附加到范围,而不是精确点。
例如,像这样的东西也可以避免相等问题:
if (temp < 7.5)
{
viscosity = (1.49 * pow(10, -6));
}
else if (temp < 12.5)
{
viscosity = (1.31 * pow(10, -6));
}
else
{
viscosity = (1.15 * pow(10, -6));
}发布于 2018-06-20 07:28:59
如果只检查那些特定值,可以将temp设为int并进行如下比较:if(temp == 5)。如果它都是.0值的话。
您还可以考虑使用switch语句,这样就不需要所有这些if语句
switch (temp)
{
case 5:
//....
break;
case 10:
//.... etc.
break;
default:
//....
break;
}https://stackoverflow.com/questions/50937249
复制相似问题