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
2009-03-20 04:49:50
+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
2009-03-20 05:34:09