百分比计算始终返回0

Jas*_*son 9 iphone xcode objective-c

我试图计算某事物的百分比.这是简单的数学.这是代码.

float percentComplete = 0;
if (todaysCollection>0) {
    percentComplete = ((float)todaysCollection/(float)totalCollectionAvailable)*100;
}
Run Code Online (Sandbox Code Playgroud)

这里todaysCollection的价值是1751 totalCollectionAvailable是4000两者都是int类型.但是percentComplete总是显示0.为什么会发生这种情况?谁能帮我吗.我是Objective C的新手.

Sim*_*ker 11

但是percentComplete总是显示0

你是如何显示percentComplete的?请记住它是一个浮点数 - 如果你把它解释为一个没有强制转换它的int你会得到错误的输出.例如,这个:

int x = 1750;
int y = 4000;
float result = 0;
if ( x > 0 ) {
    result = ((float)x/(float)y)*100;
}
NSLog(@"[SW] %0.1f", result);   // interpret as a float - correct
NSLog(@"[SW] %i", result);      // interpret as an int without casting - WRONG!
NSLog(@"[SW] %i", (int)result); // interpret as an int with casting - correct
Run Code Online (Sandbox Code Playgroud)

输出:

2010-09-04 09:41:14.966 Test[6619:207] [SW] 43.8
2010-09-04 09:41:14.967 Test[6619:207] [SW] 0
2010-09-04 09:41:14.967 Test[6619:207] [SW] 43
Run Code Online (Sandbox Code Playgroud)

请记住,将浮点值转换为整数类型只会丢弃小数点后的内容 - 因此在我的示例中,43.8呈现为43.要将浮点值舍入为最接近的整数,请使用数学中的一个舍入函数. h,例如:

#import <math.h>

... rest of code here

NSLog(@"[SW] %i", (int)round(result)); // now prints 44
Run Code Online (Sandbox Code Playgroud)


cic*_*chy 2

也许尝试使用 *(float)100,有时这就是问题所在;)

  • 很可能不是,因为只有其中一个操作数必须是浮点型,表达式才能计算为浮点型(感谢隐式转换)。不过,这只是我的明智推论。 (3认同)