Obtaining float from division between NSIntegers

BigCola picture BigCola · Sep 22, 2012 · Viewed 10.3k times · Source

I have two NSInteger variables called "domande" and "corrette". I have to execute this operation with them: corrette*10/domande. I want the result to be a float variable, so I declared a "voto" variable as so: "float voto = corrette*10/domande;" . When I output the value of "voto" with NSLog I get an approximated value of the result followed by ".000000".

Here's the code:

NSInteger domande = [numDomande integerValue];
NSInteger corrette = [numRisposteCorrette integerValue];
float voto = corrette*10/domande;
NSLog(@"float value is: %f", voto);

When I assign to "domande" a value of 7, and to "corrette" a value of 4: voto=5.000000 Instead it should be voto=5.71...

How can I have the division return not an integer type converted to float, but directly a float type?

Answer

paxdiablo picture paxdiablo · Sep 22, 2012

Simplest way is to do:

float voto = 10.0f * corrette / domande;

By making the first argument a float, you guarantee that the others will be promoted as well and that intermediate and final results will not suffer truncation.

You could achieve a similar result by casting corrette to a float but I tend to prefer simplicity where possible.