Sorry for the basic question, I have to divide the long variable by another long variable, but it returns 0. Can any one help
long a = 3004230; long b = 6793368; long c = (a/b)*100;
Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.
// Divide a literal by a literal; result is 5 int result = 10 / 2; // Divide a variable by another variable; result is 3 int a = 15; int b = 5; int result = a / b; When dividing integer types, the result is an integer type (see the previous chapter for the exact data type conversions for mathematical operations).
There are a couple of issues with that code. Firstly, non-floating point literal values are of type int
by default and so 3004230
in your code is an int
. To explicitly declare it a long
use 3004230L
instead.
Also, all arithmetic done with non-floating point literals returns an int
result unless one of the variables are casted specifically to a floating point type such as float
or double
. As such (a/b)*100
is less than 1, and therefore is truncated down to 0 (the floating point values are just cut off). Also, even if it did return the same result you are trying to store it in a long
which can not store floating point values.
So, you should do something like the following to get the real result.
long a = 3004230L; // Use the L notation to declare this literal a long. long b = 6793368L; double c = ((double)a/b)*100; /* casting one of the variables to (double) means the result will not be 0 */
I hope this helps.
final long a = 3004230; final long b = 6793368; final double c = ((double) a / b) * 100;
=> c = 44.22298335670907
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With