3

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
  • 24,318
  • 34
  • 129
  • 277
Dead_S
  • 105
  • 1
  • 2
  • 6

4 Answers4

8

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

Try with 1.0 and 2.0 instead.

trojanfoe
  • 118,129
  • 19
  • 204
  • 237
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
  • 26,460
  • 11
  • 62
  • 99
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
  • 1,887
  • 1
  • 13
  • 26
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,239
  • 5
  • 42
  • 49