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:
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! 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.
In C++ the result type of division depends on the type of the operands, NOT the type that would most accurately represent the result. 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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.