0

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?
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by gusano79
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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.