2

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?

BigCola
  • 312
  • 1
  • 4
  • 16

5 Answers5

9

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
5

Rather than converting integers to floats, you could just get floats in the first place:

CGFloat domandeFloat = [numDomande floatValue];
CGFloat corretteFloat = [numRisposteCorrette floatValue];
CGFloat voto = (corretteFloat / domandeFloat) * 10.0f
NSLog(@"float value is: %f", voto);
Abizern
  • 146,289
  • 39
  • 203
  • 257
4

NSInteger does not have a method called floatValue. NSInteger is just an int. Instead, the solution would be:

CGFloat domandeFloat = [[NSNumber numberWithInt: numDomande] floatValue];
CGFloat domandeFloat = [[NSNumber numberWithInt: numRisposteCorrette] floatValue];
CGFloat voto = (corretteFloat / domandeFloat) * 10.0f;
Rudolf J
  • 517
  • 4
  • 10
  • Actually the most correct way would be to use numberWithInteger as the source numDomande is a NSInteger, not an int – PakitoV Aug 09 '18 at 13:43
2

Try to convert the NSIntegers to a float type first:

float voto = (float)corrette*10/(float)domande;
Asciiom
  • 9,867
  • 7
  • 38
  • 57
0

you can cast "10" from int to float by writing it as "10.0"

  float voto = corrette*10.0/domande;

or

float voto = ((float)corrette*10) / (float)domande;

Operation "/" is returning type of it operands - 5/4 will return int result 1 because 5 and 4 are int, and 5.0/4.0 will return 1.25, because 5.0 and 4.0 are interpreted as float values. So you should manually cast type of input variables corrette and domande to float

medvedNick
  • 4,512
  • 4
  • 32
  • 50