0

In the calculation of double numbers, what's the difference between, say, 6.0 and 6? Because when I was solving a problem on online judge, the expression

estimatedPI = Math.sqrt(6*a/b);

got "Wrong answer" on OJ, while

estimatedPI = Math.sqrt(6.0*a/b);

got "Accepted" on OJ.

For the output, because I used

String result;
result = String.format("%.6f\n",estimatedPI);
System.out.print(result);

so the output looks exactly the same, with six digits after decimal point.

The estimatedPI is declared double and a,b declared int.

So why 6.0 got "Accepted" and 6 got "Wrong answer"? What would be the difference here?

Thanks.

Edit: Noted of duplicated questions.

Huanyan
  • 85
  • 1
  • 7

2 Answers2

1

6.0 is a double. 6 is an int.

If a and b are also ints, then 6*a/b is not a "double calculation" - it will be done using int arithmetic.

When you mix doubles and ints in a binary mathematical operation, the int is converted to a double and then the operation is done using double arithmetic. So 6.0*a does a double multiplication (converting a to double first), resulting in a double. Then (the result of that)/b also does a double division (converting b to double first).

user253751
  • 57,427
  • 7
  • 48
  • 90
0

The .0 is an indicator to the compiler that the constant is a floating point number rather than an integer. Your expression 6 * a / b will be treated as an integer expression.

sprinter
  • 27,148
  • 6
  • 47
  • 78