Douglas
Douglas

Reputation: 2524

Comparison operators not working correctly Xcode

I am making a grading App for my students, but my comparison operators are not functioning they way I expect them to. My code is as follows;

float FINAL = ((_gradeyouwant - (_quarter1 * 0.2f) - (_quarter2 * 0.2f) - (_quarter3 * 0.2f) - (_quarter4 * 0.2f) - (_quarterM * 0.1f)) / 0.1f);

NSLog(@"q1 = %.2f", _quarter1);
NSLog(@"q2 = %.2f", _quarter2);
NSLog(@"q3 = %.2f", _quarter3);
NSLog(@"q4 = %.2f", _quarter4);
NSLog(@"qM = %.2f", _quarterM);
NSLog(@"qF = %.2f", FINAL);
NSLog(@"grade = %.2f", _gradeyouwant);

if ((FINAL > 4.3f))
{
    [_result setText:[NSString stringWithFormat:@"It is not possible to get your desired grade."]];
}else if ((FINAL > 4.0f))
{
    [_result setText:[NSString stringWithFormat:@"You would need to get an A+"]];
}else if ((FINAL > 3.7f))
{
    [_result setText:[NSString stringWithFormat:@"You would need to get an A"]];
}else if ((FINAL > 3.3f))

ETC. ETC.

When you look at the output with NSLog, it tells me the correct value of everything. However, if I make it so the FINAL is 4.0, it does not print the correct string. I was figuring that when it got to the FINAL > 4.0, it would not run that line. But it does. What am I doing wrong? Thanks so much in advance!

Upvotes: 0

Views: 232

Answers (1)

Norman
Norman

Reputation: 453

This is pretty much how floats work. Google it, e.g. http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

The system may not be able to precisely store 4.0. It's more a limitation of your CPU and choice of data types. Using a range may very well work.

I'd use an int and emulate the decimal digits, e.g. GPA * 100.

Upvotes: 1

Related Questions