0
#iclude <iostream>
#include <cmath>
#include <math.h>
using namespace std;

int main()
{
    double speed = 5;
    int temp = -5;
    int windChill;
    double roundedWindChill;

    windChill = ((35.74 + (0.6215 * temp) - (35.75 * pow(speed, 0.16)) + (0.4275 * temp *   (pow(speed0.16)))) * 10.0) + 0.5;
    roundedWindChill = windChill / 10.0;
        cout << roundedWindChill;
}

When I run this I get 16.3, however I should be getting 16.4 because the answer with an additional figure would be 16.37. Not sure why this is not rounding.

Thanks for the help!

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 3
    Why would division by 10 perform rounding? – Jeffrey Feb 13 '23 at 01:03
  • 1
    Float-to-integer conversion doesn't round. It truncates. Add 0.5 to round. – Silvio Mayolo Feb 13 '23 at 01:05
  • Converting floating point to `int` always rounds towards zero. It doesn't round to the nearest integer. Either add `0.5` or (since C++11) use `std::round()` or `std::lround()`. – Peter Feb 13 '23 at 01:13
  • Does this answer your question? [C++: How to round a double to an int?](https://stackoverflow.com/questions/9695329/c-how-to-round-a-double-to-an-int) – JaMiT Feb 13 '23 at 03:56
  • The problem is a *bit* more subtle than some of the above comments suggest. The loss of precision occurs in the line before the division by 10: that gives an integer result of -163, so there is no possibility of recovering the lost `7` after that point. – Adrian Mole Feb 13 '23 at 10:16
  • @AdrianMole *"The problem is a bit more subtle than some of the above comments suggest."* -- also suggested by the choice of the name `roundedWindChill`. ;) If the OP had chosen more accurate names for the variables, maybe the first comment would not have been made. – JaMiT Feb 14 '23 at 03:37
  • It should be noted that the cute `x+.5` does not round negative numbers correctly. – Friedrich Feb 14 '23 at 09:56

1 Answers1

0

Due to integer division rules in C++, the result is truncated towards zero.

Suppose we have the following code:

int a = 8;
int b = 3;
int c = a / b;

The value would be 2.

In your code, the expression windChill / 10.0 is performing such division, which discards any decimal places and rounds the result down to the nearest integer.

To fix this, use std::round() from the <cmath> library to round windChill before dividing by 10.0.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double speed = 5;
    int temp = -5;
    int windChill;
    double roundedWindChill;

    windChill = round((35.74 + (0.6215 * temp) - (35.75 * pow(speed, 0.16)) + (0.4275 * temp * (pow(speed,0.16)))) * 10.0);
    roundedWindChill = windChill / 10.0;
    cout << roundedWindChill;
}
headfxll
  • 35
  • 1
  • 1
  • 8