Reputation: 15052
I haven't been able to find these rules on a website, (surely because I'm googling the wrong thing) so I'm asking here.
Dividing an int by an int and storing in a double always stores the rounded integer first. The only way I've been able to find to make it work is to cast both values to a double before doing the divide. There's got to be a better way.
Also, where are the rules for the return types?
Upvotes: 2
Views: 443
Reputation: 56059
Sure there's a better way. Just cast one of them to a double
, the other will be converted automatically.
The type of the expression is determined by the arguments before it is stored, so as other answers state, an int
divided by an int
yields an int
, which will only then be stored as a double
. Note that this is not specific to Java, it happens in every language I know of that does integer division.
Upvotes: 0
Reputation: 533500
You only need to cast one argument to make the result a double
int a,b;
double d = (double) a / b;
a simpler approach is to use doubles from the start.
double a, b;
double d = a / b;
double
can represent every possible int
value without a rounding error.
Possible duplicate: How to divide two large integers in java?
Upvotes: 1
Reputation: 10285
In an programming language, there are 2 types of operations:
If the 2 operands are of Integer type, the Integer operation is executed.
If ANYONE of the 2 operands is of Floating Point, the Floating Point Operation is exectued.
THUS:
Int / Int --------> int
Double / Int -----> Double
Double / Double --> Double
Upvotes: 3
Reputation: 112366
Actually, no there doesn't have to be a better way. Dividing an int by an int results in an int. So, say you divide 5/2 -- since there's no integer between 2 and 3, you get 2. if you want a floating-point result, you need to make one of them a floating type; instead of
int f=5, t=2;
double result;
result = f/t;
make it
result = f / (double) t ;
using a type cast to tell it "I want floating point division dammit!".
Upvotes: 4