0

Noob Question.

double answer = 13/5;
System.out.println(answer);

Why does that return 2 instead of 2.6.

As in must i say (double) 13/5 everytime i want to print a double.

  • It's got nothing to do with printing. The problem is that you're performing integer division - both of the operands of `13/5` are integers. The integer result is then being promoted to a `double`. I'll see if I can find a duplicate - this has come up several times. – Jon Skeet May 02 '15 at 19:08
  • Q: must i say (double) 13/5 everytime i want to print a double? A: Yes. Or, better, `double answer = 13.0/5.0;`. You *MUST* have a double operand in your expression to evaluate a double result. – FoggyDay May 02 '15 at 19:08
  • In addition to the answers already posted, you could also do this: `double answer = 13d/5d;` – Daniel Nugent May 02 '15 at 19:11
  • `double answer 13.0 / 5.0` would solve your problem. If you want to verify that `System.out.println` is not the problem, read that: https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28float%29 – Shondeslitch May 02 '15 at 19:11

4 Answers4

0

you must tell java that you want a double division:

double answer = 13/5.0; // or 13 / (double) 5.0
Farnabaz
  • 3,980
  • 1
  • 20
  • 42
0

13 and 5 are integers. That means that you divide them as integers. As a result, you will get an integer. So what you have to do is to cast them as double like that:

double answer = 13 / (double) 5;

Or write them like that:

double answer = 13 / 5.0;
yemerra
  • 1,292
  • 2
  • 16
  • 43
0

Because 13 and 5 are integers, so the result will be an integer that you are assigning to a double variable

You need to specify your numbers should be considered as double

Alexandru Severin
  • 5,609
  • 10
  • 40
  • 67
0

The division takes place between two ints and the result is also an int which is finally cast into a double. You should declare the operands as doubles to get the desired result.

Mick Mnemonic
  • 7,638
  • 2
  • 24
  • 30