954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Objective-C strange result

Hi guys,

I am learning Objective-C and today at night I managed a simple program, an usual one from ordinary exercise.

Code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"Welcome to multiplication table test");
    int rightAnswers; //the sum of the right answers
    int wrongAnswers; //the sum of wrong answers
    int combinations; //the number of combinations
    
    
    NSLog(@"Please, input the number of test combinations");
    scanf("%d",&combinations);
    
    for(int i=0; i<combinations; ++i)
    {
        int firstInt=rand()%8+1;
        int secondInt=rand()%8+1;
        int result=(int)firstInt*secondInt;
        int answer;
        
        
        NSLog(@"%d*%d=",firstInt,secondInt);
        scanf("%d",&answer);
        if(answer==result)
        {
            NSLog(@"Ok");
            rightAnswers++;
        }
        else
        {
            NSLog(@"Error");
            wrongAnswers++;
        }
    }
    int percent=(100/combinations)*rightAnswers;
    NSLog(@"Combinations passed: %d",combinations);
    NSLog(@"Answered right: %d times",rightAnswers);
    NSLog(@"Answered wrong: %d times",wrongAnswers);
    NSLog(@"Completed %d percent",percent);
    if(percent>=70)NSLog(@"accepted");
    else
        NSLog(@"failed");
    [pool drain];
    return 0;
}

Well, if I input 3 combinations and complete 'em right, I am not getting 100%. Getting only 99%. Why?
If I count it on calculator it makes 100/3=33.3333333*3=100

Can somebody to explain to me, to absolute beginner?
Nfurman
Junior Poster in Training
69 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 
if I input 3 combinations and complete 'em right, I am not getting 100%. Getting only 99%. Why? If I count it on calculator it makes 100/3=33.3333333*3=100

It sounds like you're running into floating point accuracy issues in this line:

int percent=(100/combinations)*rightAnswers;


If the actual value of (100/combinations)*rightAnswers is less than 100.0, the conversion to int truncates the fractional part.

If you make percent a floating point value instead of an integer, you can see the actual answer returned, which I expect looks something like 99.9999991892311047981203 (or whatever, I made up those digits). If you use the round function from math.h , that should fix you up.

gusano79
Posting Pro
521 posts since May 2004
Reputation Points: 182
Solved Threads: 77
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: