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? and round up or down? Must be: (1/10) * 3 = 0.1 * 3 = 0.3 = 0 and (4/10) * 3 = 0.4 * 3 = 1.2 = 1
Thanks a lot!
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
1/10
This line returns 0.so 0 * 3 = 0. Use double instead of int
since both a and b are integers, so the output will also be int, which makes 1/10 equal to 0, and then 0 * 3 = 0
Try:
int d = (int) (((double)4/10)*3);
You want to perform a calculation using a floating point view. Then you can return the result to an integer.
I note that you are referring your question to rounding up / down.
Math.round () will help you here.
Returns the closest long argument. The result is rounded to an integer, adding 1/2, taking the floor of the result and running for long input.
It will work
int a = 1; int b = 10; int c = 3; int d = (1*3/10); System.out.println(d);