4

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.

leeand00
  • 25,510
  • 39
  • 140
  • 297
Dead_S
  • 115
  • 1
  • 2
  • 6

4 Answers4

9

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

Try with 1.0 and 2.0 instead.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

In (1 / 2) both the 1 and 2 are integers which means that the result is also an integer. This means the expression returns 0. 0 * 2 is 0.

To get the result you want, try (1.0 / 2.0)

doron
  • 27,972
  • 12
  • 65
  • 103
1

If you want to get right result you need to write:

#include <iostream>

using namespace std;

int main()
{
  double test = ((double)1 / 2) * 2;
  cout << test << endl;
  return 0;
}
Ashot Khachatryan
  • 2,156
  • 2
  • 14
  • 30
0

You're using int instead of double.

Fixing...

#include <iostream>

using namespace std;

int main()
{
    double test = (1.0 / 2.0) * 2.0;
    cout << test << endl;
    return 0;
}
Tarod
  • 6,732
  • 5
  • 44
  • 50