C++ C++;:温度转换器-为什么计算返回0

C++ C++;:温度转换器-为什么计算返回0,c++,C++,为什么k值返回0?请帮忙 double fah, kel; fah = std::atof(input.c_str()); //convert string input to a double & assign value to be fah degree kel = (double)((f + 459.67) * (5/9)); //calculate fah temp to kelvin 当整数加上除法时,“P>K”值为0,C++中的 < P>, 5/9=0</COD>整数

为什么k值返回0?请帮忙

double fah, kel;

fah = std::atof(input.c_str());  //convert string input to a double & assign value to be fah degree 
kel = (double)((f + 459.67) * (5/9)); //calculate fah temp to kelvin 

当整数加上除法时,“P>K”值为0,C++中的

< P>,<代码> 5/9=0</COD>整数除法。< /P>
使用
5.0/9

问题是整数除法。其结果是:

5/9
0
。应使用浮点类型:

5/9.0 // 9.0 is a double.

表达式5/9具有整数类型,即其结果等于0。
将(5/9)至少更改为(5.0/9)

这是一个整数除法问题。此外,您可以稍微简化方程式:

Dk = C*Df + C*B ===> Dk = C*Df + A
其中,
Dk
是开尔文度,
Df
是法伦海特度,
C
5/9
常数,
A
C*开尔文偏移量
(也是常数)。这将使您的代码:

const double FtoKMultiplier = 5.0/9.0; // done at compile time
const double FtoKOffset = 459.67 * FtoKMultiplier; // also done at compile time
double fah = std::atof(input.c_str());
double kel = FtoKMultipler * fah + FtoKOffset; // single multiplication and addition at runtime

为什么这两个数字中只有一个必须是十进制形式?@user2925557除法运算符
/
的一个操作数为浮点(FP)类型就足以在FP中计算运算(运算结果为FP)@用户2925557
int/double
double/int
的操作将自动升级为
double
结果。为了可读性,通常最好将两者都作为双精度格式编写,但这不是必需的。