划分错误的结果

时间:2011-01-09 15:47:34

标签: iphone objective-c integer-division

我试图划分整数但结果得到0。我只是不明白我做错了什么。我在这个例子中只使用了int,但是使用float或double进行相同的结果测试。

我使用的代码是:

int wrongAnswers = askedQuestions - playerResult;
int percentCorrect = (playerResult / askedQuestions) * 100;
int percentWrong = (wrongAnswers / askedQuestions) * 100;


NSLog(@"askedQuestions: %i", askedQuestions);
NSLog(@"playerResult: %i", playerResult);
NSLog(@"wrongAnswers: %i", wrongAnswers);
NSLog(@"percentCorrect: %i", percentCorrect);
NSLog(@"percentWrong: %i", percentWrong);
NSLog(@"calc: %i", (wrongAnswers + playerResult));
NSLog(@"wrong answers %: %i %%", ((wrongAnswers / askedQuestions) * 100));

我得到的结果是:

  

2011-01-09 16:45:53.411 XX [8296:207]问题:5
  2011-01-09 16:45:53.412 XX [8296:207] playerResult:2
  2011-01-09 16:45:53.412 XX [8296:207] wrongAnswers:3
  2011-01-09 16:45:53.413 XX [8296:207] percentCorrect:0%
  2011-01-09 16:45:53.414 XX [8296:207]%错误:0%
  2011-01-09 16:45:53.414 XX [8296:207] calc:5
  2011-01-09 16:45:53.415 XX [8296:207]错误答案:0%

我非常感谢帮助: - )

4 个答案:

答案 0 :(得分:7)

你首先得到0(完全失去价值)然后乘以它。你需要首先乘以,然后除。

答案 1 :(得分:2)

尝试使用float数据类型,int被截断。

答案 2 :(得分:2)

将分区转换为十进制。 Int除以int将向上舍入为0。

percentCorrect = ((decimal) playerResult / (decimal) askedQuestions) * 100;

答案 3 :(得分:1)

你使用int来存储结果,这意味着如果除法产生的值为0.8,则值被截断,你将得到0作为答案

相关问题