문제

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