我學習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