C ++ numbers are not rounded correctly

I am new to Qaru and generally programming. I participate in several C ++ programming classes and come across a task that I am having problems with. This program should take Fahrenheit and transform it into a target. I saw other programs, but could not find a duplicate for my specific 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 works great on 4 of the 5 tests that run. It is rounded from 22.22 to 22 and from 4.44 to 4, as expected, but when 0 F is entered, it is rounded from -17.77 to -17 instead of -18. I worked for about an hour and will be happy to help! Thank.

+4
source share
4 answers

Integers are implicitly rounded, as are casts to integer types.

, float int :

#include <iostream>
using namespace std;

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

    return 0;
}

( , "14.25", e), std::fixed cout . cout.precision(), , .


- int, std::round() .

+2

std::round() , double int. , , double.

: , , ( ).

+5

When the compiler converts a floating point number to an integer, it is not rounded, it is truncated. That is, it simply reduces the numbers after the decimal point. Thus, your program behaves the way it is programmed.

+2
source
int x = 3.99;
int y = std::round(3.99);
std::cout 
   << "x = " << x << std::endl
   << "y = " << y << std::endl
   ;

--> 
x = 3
y = 4

C / C ++ does not do a floating point round when static_cast<int>-fields are float in int. If you want to round, you need to call the library functionstd::round()

0
source

All Articles