Converting Fahrenheit to Celsius rounding error
Jan 19, 2017 at 8:00am Jan 19, 2017 at 8:00am UTC
I'm trying to write a temperature converter for my class but whenever I put it through testBed I have a rounding error and have no idea how to fix it. testBed puts the code through 5 tests, which it passes all but one. When you put in 0 fahrenheit it comes out to -17.777 Celsius, so it is expecting it to round to -18 but my code rounds it to -17. I've looked, but can't seem to find out how to get it to round correctly... Does anyone have any hints or help for me?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declare variables
int f;
int c;
//Ask for inputs
cout << "Please enter Fahrenheit degrees: " ;
cin >> f;
cout << setprecision(3);
//Display input in celsius
c = 5.0 / 9 * (f-32);
cout << "Celsius: " << c << endl;
return 0;
}
Jan 19, 2017 at 8:19am Jan 19, 2017 at 8:19am UTC
use round function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
//Declare variables
float f;
float c;
//Ask for inputs
cout << "Please enter Fahrenheit degrees: " ;
cin >> f;
cout << setprecision(3);
//Display input in celsius
c = 5.0 / 9 * (f - 32);
cout << "Celsius: " << round(c) << endl;
system("pause" );
}
Last edited on Jan 19, 2017 at 8:19am Jan 19, 2017 at 8:19am UTC
Jan 19, 2017 at 8:30am Jan 19, 2017 at 8:30am UTC
Thank you! I didn't know there was a round function...
Jan 19, 2017 at 12:02pm Jan 19, 2017 at 12:02pm UTC
Hello ripken2,
I once solved this problem by setting "setprecision(0)" before the output of the actual number.
Hope that helps,
Andy
Jan 19, 2017 at 3:00pm Jan 19, 2017 at 3:00pm UTC
You will also have fewer "rounding errors" if you use a double instead of a float for your numbers.
Topic archived. No new replies allowed.