I am doing a simple homework assignment and having a problem with my computation. The answer to my calculator is 4.83, but my compiler says 4.00. How can correct this? Here is the part where I am having difficultly.

double test = 29/6;
 System.out.printf("%.2f",test);
 System.out.println(test);
有帮助吗?

解决方案

If you divide two integers result is always integer

You have to cast one number from int to double.

 double test = (double)29/6;
 System.out.printf("%.2f",test);
 System.out.println(test);

Note that if you just write number, it is considered int

There is important thing, following code prints 4.00 too :

 double test = (double)(29/6);
 System.out.printf("%.2f",test);
 System.out.println(test);

Because first it divides two integers, therefore the result is also integer and then it is casted to double.

Using (double)29/6 is same as ((double)29)/6, because casting has higher priority.

其他提示

It's because both operands of division are int, therefore the whole result is truncated to type int. Make the operands double such as this and all works fine.

double test = 29.0/6.0;

It's doing integer division, which truncates everything to the right of the decimal point , hence you are getting 4.

Try the below :

double test = 29.0/6;             
    System.out.printf("%.2f",test);
    System.out.println(test);

Output :

4.83
4.833333333333333
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top