2

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Thom
  • 14,013
  • 25
  • 105
  • 185

4 Answers4

4

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!".

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
3

In an programming language, there are 2 types of operations:

  • Integer Operations
  • Floating Point Operations (Float, Double)

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
Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
1

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?

Community
  • 1
  • 1
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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.

Kevin
  • 53,822
  • 15
  • 101
  • 132