【发布时间】:2011-07-12 00:01:48
【问题描述】:
我正在学习Objective-C,完成了一个简单的程序,得到了意想不到的结果。这个程序只是一个乘法表测试......用户输入迭代次数(测试题),然后输入答案。之后程序显示正确和错误答案的数量、百分比和接受/失败的结果。
#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=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,那么这是一个快乐的巧合,而不是一个保证的事实。 -
没有帮助!它仍然使99%。在我的早期版本中,它们已被初始化。
-
是的,我不认为它会有所帮助。我只是警告你避免未来的问题,因为依赖这样的未定义行为是让你的程序最终爆炸的好方法。您获得 99 的原因在下面的答案中进行了解释。
标签: objective-c