问题
int a = 1; int b = 10; int c = 3; int d = (1/10)*3 System.out.println(d) Result: 0
How do i make this Calculation work ? and round up or down ? It should be: (1/10)*3 = 0.1 * 3 = 0.3 = 0 and (4/10)*3 = 0.4 * 3 = 1.2 = 1
Thanks a lot!
回答1:
1 / 10
This is integer division and as integer division the result is 0. Then 0 * 3 = 0
You can use double literals:
1.0 / 10.0
回答2:
Try:
int d = (int) (((double)4/10)*3);
回答3:
1/10
This line return 0.so 0*3=0.Use double instead of int
回答4:
as both a and b are integer so the output will also be int which makes 1/10 as 0 and then 0*3=0
回答5:
You will want to perform the calculation using floating-point representation. Then you can cast the result back to an integer.
回答6:
I note that you refer in your question to rounding up/down.
Math.round() will help you here.
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long.
回答7:
This will works
int a = 1;
int b = 10;
int c = 3;
int d = (1*3/10);
System.out.println(d);
来源:https://stackoverflow.com/questions/12105494/java-double-integer