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;
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;
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
try it.
long a = 3004230;
long b = 6793368;
long c = ((long)((float)a/(float)b)*100); //answer=44
float c = ((long)((float)a/(float)b)*100); //answer=44.1256378
obviously the answer will be 0
for above..as you can see when you divide
3004230 / 6793368 = 0.442 = 0(when casted to
long
type)
and
0 * any number = 0..
to convert it use this
double c = (a * 1.0/b)*100.0;
you have to use datatype that can store decimal
value which is float
or double
..long
cannot store decimal numbers
You can do the same without casting to a float
:
long a = 3004230L;
long b = 6793368L;
long c = (a * 100L)/b;
What you are doing right now is integer division. This will always return an integer/long result. You have to use a float or double to get a floating point result even if you cast it back to integer values afterwards.
long c = (long)(a/(float)b*100);
The long c you are creating isn't the value you expected. It is in the integer range. To create longs, use
final long c= 3004230L * 6793368L; By adding an L after the number literal, you tell the compiler to compile it as a long instead of an int.