Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ why does ((1 / 2) * 2) return 0 [duplicate]

Tags:

c++

first time I'v posted here but I must know what's wrong with this simple peace of code:

#include <iostream>

using namespace std;

int main()
{
    double test = (1 / 2) * 2;
    cout << test << endl;
    return 0;
}

when ever I run this the code it displays 0, should I be casting something, it happens regardless of what compiler I use and it returns even stranger results if the '1' is divided be some form of decimal.

like image 539
Dead_S Avatar asked Oct 21 '25 20:10

Dead_S


1 Answers

Because in integer maths 1 / 2 == 0 and 0 * 2 == 0.

Try with 1.0 and 2.0 instead.

like image 199
trojanfoe Avatar answered Oct 23 '25 11:10

trojanfoe