tags:

views:

2140

answers:

3

Hi : I want to know how to get remainder and quotient in single value in java. Example 3/2 i should value as 1.5. If i use "/" operator, getting only quotient and for "%" operator, getting only remainder value. How do i get both at a time?

+5  A: 

In your example, Java is performing integer arithmetic, rounding off the result of the division.

Based on your question, you would like to perform floating-point arithmetic. To do so, at least one of your terms must be specified as (or converted to) floating-point:

Specifying floating point:

3.0/2
3.0/2.0
3/2.0

Converting to floating point:

int a = 2;
int b = 3;
float q = ((float)a)/b;

or

double q = ((double)a)/b;

(See Java Traps: double and Java Floating-Point Number Intricacies for discussions on float and double)

Cheers, V.

vladr
+4  A: 
quotient = 3 / 2;
remainder = 3 % 2;

// now you have them both
recursive
+4  A: 

Don't worry about it. In your code, just do the separate / and % operations as you mention, even though it might seem like it's inefficient. Let the JIT compiler worry about combining these operations to get both quotient and remainder in a single machine instruction (as far as I recall, it generally does).

Neil Coffey