Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

division

I'm using this:

NumberFormat formatter = new DecimalFormat("##.##");
double nota=(punctaj / nr_intrebari)*10;
String notafinala=formatter.format(nota);

where punctaj and nr_intrebari are int

Why nota or notafinala is 0 (zero) is the result of the division is not an integer?
For example, if punctaj=1 and nr_intrebari=3 then nota=0.0.Why? I want the result to be a double like 0,33.
[426 byte] By [wasssu] at [2007-11-11 8:48:20]
# 1 Re: division
Your trouble is with this line:

double nota=(punctaj / nr_intrebari)*10;

Because punctaj and nr_intrebari are int's, then 1/3 = 0 -> you're doing integer division. Integer division discards the remainder. 1/3 = 0.333... so the integer answer is 0. 6/5 = 1.2 so the integer answer is 1.

If you want the result as a double, you have to cast.

Try this:

double nota=(punctaj / (double)nr_intrebari)*10;

The (double) tells the compiler that you want to evaluate the integer division as if it were floating point division.
masher at 2007-11-11 22:34:23 >