本文介绍了iOS int总是返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小计算,但它总是返回0 ..

I am doing a small calculation but it always returns 0..

    int totalBothTeams = [prefs integerForKey:@"totalTimeBothTeams"];
    int someCalculation = (totalBetween / totalBothTeams) * 100;

    NSLog(@"Time: %i", someCalculation);

任何想法?

推荐答案

我假设 totalBetween 小于 totalBothTeams - 在这种情况下分组

I am assuming that totalBetween is less than totalBothTeams - in which case the division

totalBetween / totalBothTeams

导致整数值 0

如果您正在寻找百分比类型的答案,你可以在分组前乘以100。你仍然会四舍五入。或者你可以用双精度完成整个事情并在结尾投射:

If you are looking for a "percentage" type of answer, you can multiply by 100 before taking the division. You will still get "rounding down". Or you can do the whole thing in double precision and cast at the end:

(totalBetween * 100) / totalBothTeams

(totalBetween * 100.0) / totalBothTeams + 0.5




  • 后者将舍入正确

  • 这篇关于iOS int总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:12