我学习Objective-C和已经完成了一个简单的程序,并得到了一个意想不到的结果。这个程序只是一个乘法表测试...用户输入迭代次数(测试问题),然后输入答案。程序显示正确和错误答案的数量,百分比和接受/失败的结果。的Objective-C:奇怪的计算结果
#import <Foundation/Foundation.h>
INT主(INT的argc,常量字符* 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 [email protected]
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=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;
}
问题(奇怪结果)
当我输入3次迭代和答案他们是对的,我没有100%的权利。只获得 99%。我在iPhone计算器上试过的次数也是一样。
100/3 = 33.3333333 ...百分比一个正确的答案(程序将显示33%。尾数后面的数字被截断)
33.3333333 ... * 3 = 100%
可有人解释我哪里出错了?感谢名单。
这似乎与您的问题没有关系,但您需要初始化您的变量。如果在代码开始时'rightAnswers'和'wrongAnswers'确实为0,那么这是一个令人高兴的巧合,而不是一个有保证的事实。 – Chuck
不帮忙!它仍然是99%。在我的早期版本中,它们已初始化。 – NCFUSN
是的,我没有想到它会有所帮助。我只是警告你避免将来出现问题,因为依赖这种未定义的行为是使程序最终爆发的好方法。你得到99的原因在下面的答案中解释。 – Chuck