Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ numbers aren't rounding correctly

Tags:

c++

I am new to Stack Overflow, and programming in general. I am in a few classes for programming C++ and have come across an assignment I am having a bit of trouble with. This program is supposed to take fahrenheit and convert it to celsius. I have seen other programs, but could not find a duplicate to my particular problem. This is my code.

#include <iostream>
using namespace std;

int main()
{
    int fahrenheit;
    cout << "Please enter Fahrenheit degrees: ";
    cin >> fahrenheit;
    int celsius = 5.0 / 9 * (fahrenheit - 32.0);
    cout << "Celsius: " << celsius << endl;

    return 0;
}

So this is working great on 4 of the 5 tests that are run. It rounds 22.22 to 22 and 4.44 to 4 like it should, but when 0 F is put in, it rounds -17.77 to -17 instead of -18. I have been researching for about an hour and would love some help! Thank you.

like image 674
Ethan Adams Avatar asked Jan 07 '23 05:01

Ethan Adams


1 Answers

Use std::round() instead of relying on the implicit conversion from double to int. Either that, or do not use conversion at all, show the temperature as a double.

EDIT: As others already pointed out, implicit conversion will not round but truncate the number instead (simply cut off everything after the decimal point).

like image 198
Vucko Avatar answered Jan 19 '23 20:01

Vucko