简体   繁体   English

双功能仅返回-0

[英]double function only returning -0

I have two functions as part of a larger function I'm writing as an exercise. 我有两个函数是作为练习编写的更大函数的一部分。 The purposes of the functions are to convert temperatures from Fahrenheit to Celsius and vice versa. 功能的目的是将温度从华氏温度转换为摄氏温度,反之亦然。

I start with: 我从开始:

#include <iostream>
using namespace std;
double Celsius_to_Fahrenheit(double);
double Fahrenheit_to_Celsius(double);

The Celsius-to-Fahrenheit works fine: 摄氏到华氏度的效果很好:

double Celsius_to_Fahrenheit(double C){
    double F = ((9 / 5)*C + 32);
    return F;
}

But the Fahrenheit-to-Celsius function returns -0 no matter what argument it takes: 但是,无论采用何种参数,华氏度到摄氏温度函数都将返回-0

double Fahrenheit_to_Celsius(double F){
    double C = ((5 / 9)*(F - 32));
    return C;
}

What's wrong with the second? 第二个怎么了? I can't see any difference in structure that would cause one to work and not the other. 我看不到任何结构上的差异会导致一个工作正常,而另一个工作无效。

edit: I only tested the functions on 0 , both functions break for non trivial arguments! 编辑:我只测试了0上的函数,两个函数对于非平凡的参数都会中断! That's even worse! 更糟的是!

Actually I believe BOTH functions fail. 实际上,我相信这两个功能都会失败。 You just don't notice that C-to-F fails because you get a nonzero result back. 您只是没有注意到C-to-F失败,因为您返回的结果非零。

In C++ the result type of division depends on the type of the operands, NOT the type that would most accurately represent the result. 在C ++中,除法的结果类型取决于操作数的类型,而不是最能准确表示结果的类型。 In other words, 5/9 is integer division , and will be truncated down to 0. If you use something like 5.0/9.0 it will do the math as double precision and most likely give you a result that you're desiring. 换句话说,5/9是整数除法 ,并且将被截断为0。如果使用5.0 / 9.0之类的值,它将做为双精度数学运算,并且很可能会给出您想要的结果。

If however you're content with a truncated result you can just rearrange the terms to make it do the rounding as late a possible: double C = ((F - 32) * 5 / 9); 但是,如果您对截断的结果感到满意,则可以重新排列条件以使其尽可能地舍入: double C = ((F - 32) * 5 / 9);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM