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.

2
  • Because 1 and 2 are ints. And by default, all numbers are ints. Commented May 12, 2015 at 10:23
  • 4
    In OP's defense, this is really hard to search for. Commented May 12, 2015 at 10:25

4 Answers 4

9

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

Try with 1.0 and 2.0 instead.

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

It's enough to .0 only one side.
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; } 

2 Comments

Explanation needed. Also it's enough to cast only one side, the other will be implicitly cast.
Also, don't use C-style casts.
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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.