round up or down

it's strange that when I type 2.4 or 2.2 for example I get the output 3 but when I type 2.5 in 2 gets returned which I expected,but I expected 2 to be printed when I typed anything less than < 5,when I type in 2.> 5 it outputs 3 which I want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  #include <iostream>

using namespace std;

int roundNumber(double x){

if(x + 0.5 == (int)x+1){

    cout << "number is a half" << endl;
    cout << "so for the sake of it we will round down" << endl;
    x = (int) x;
    return x;
    }
    if(x + 0.6 == (int)x+1){

        x = (int) x;
        return x;
    }
    if(x + 0.7 == (int)x+1){

        x = (int)x;
        return x;
    }
    if(x + 0.8 == (int) x+1){

        x = (int)x;
        return x;
    }
    if(x + 0.9 == (int) x+1){

        x = (int)x;
        return x;
    }
    if(x + 0.4 == (int) x+1){

        x = (int)x+1;
        return x;
    }
    if(x + 0.3 == (int) x+1){

        x = (int)x+1;
        return x;
    }
    if(x + 0.2 == (int) x+1){

        x = (int)x+1;
        return x;
    }
    if(x + 0.1 == (int) x+1){

        x = (int)x+1;
        return x;
    }
}

int main()
{
    cout << "enter a double " << endl;
    double x;
    cin >> x;

    x = roundNumber(x);
    cout << x << endl;
}
It sort of works for me, but if the decimal is greater than 10 it's not working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

C:\Temp>test123
enter a double
2.1
2

C:\Temp>test123
enter a double
2.2
2

C:\Temp>
C:\Temp>test123
enter a double
2.11
3

C:\Temp>test123
enter a double
2.9
3


if you change line 5 to
double roundNumber(double x){
I think you'll get better results, but it still not correct.
Hopefully that will help you find a solution.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cmath>

long long round_number( double value ) // invariant: within the range of long long
{ return value + ( value<0 ? -0.5 : +0.5 ) ; }

int main()
{
    std::cout << std::fixed << std::showpos  ;

    for( double v : { 0.0, 1.0, -1.0, 2.4999, -2.4999, 2.5, -2.5, 2.9999, -2.9999 } )
        std::cout << v << ' ' << round_number(v) << ' ' << std::llround(v) << '\n' ;
        // http://en.cppreference.com/w/cpp/numeric/math/round
}

http://coliru.stacked-crooked.com/a/dbd968fbbe48fb1b
thanks JL and Samuel,

and yeah that's strange Samuel maybe different compilers give different results for some odd reason
Topic archived. No new replies allowed.