0

I have the following code snippet:

public class YourClassNameHere {
public static void main(String[] args) {
double x = 3 / 2 * 3;
System.out.printf("%.1f", x);
   }
}

I do know that 3.0 will be printed. However, why isn't it 4.5?

I thank you for your time and clarifications in advance.

4 Answers4

0

I recommend that you have to use proper parenthesis to minimize error double x = (3/2)*3

3\2 gives an integer value i.e 1 and to make it double you have to do (3\2.0) it gives double value i.e. 1.5 then 1.5 * 3 = 4.5

Rishabh Jain
  • 174
  • 1
  • 7
0

Because you are using Ints which will return whole numbers. To get the desired result simply add an "f" suffix to denote that the numbers are floating point:

double x = 3f / 2f * 3f;

king jaja
  • 21
  • 5
0

Your equation is double x = 3 / 2 * 3 and x variable is store double data type but 3 and 2 and 3 is store in integer format...

first you need to convert this number in double then you get right output

example:

public class YourClassNameHere {
   public static void main(String[] args) {
     double a = 3;
     double b = 2;
     double c = 3;
     double x = a / b * c;
     System.out.printf("%.1f", x);
   }
}
Faheem azaz Bhanej
  • 2,328
  • 3
  • 14
  • 29
0

Just got it, it is because 3/2 = 1, in which then 1*3 becomes 3. Thank you all for the replies!