xcode 百分比计算总是返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3640996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Percentage Calculation always returns 0
提问by Jason
I am trying to calculate the percentage of something. It's simple maths. Here is the code.
我正在尝试计算某物的百分比。这是简单的数学。这是代码。
float percentComplete = 0;
if (todaysCollection>0) {
percentComplete = ((float)todaysCollection/(float)totalCollectionAvailable)*100;
}
Here the value of todaysCollection is 1751 and totalCollectionAvailable is 4000. Both are int. But percentComplete always shows 0. Why is this happening? Can any one Help me out. I'm new to Objective C.
这里 todaysCollection 的值是 1751,totalCollectionAvailable 是 4000。两者都是 int。但是percentComplete 总是显示0。为什么会这样?谁能帮我吗。我是目标 C 的新手。
回答by Simon Whitaker
But percentComplete always shows 0
但是percentComplete 总是显示0
How are you displaying percentComplete? Bear in mind it's a float - if you interpret it as an int without casting it you'll get the wrong output. For example, this:
你是如何显示百分比完成的?请记住它是一个浮点数 - 如果您将其解释为 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
Outputs this:
输出这个:
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
Bear in mind that casting a floating point value to an integer type just discards the stuff after the decimal point - so in my example 43.8 renders as 43. To round the floating point value to the nearest integer use one of the rounding functions from math.h, e.g.:
请记住,将浮点值转换为整数类型只会丢弃小数点后的内容 - 因此在我的示例中 43.8 呈现为 43。要将浮点值四舍五入到最接近的整数,请使用数学中的舍入函数之一。 h,例如:
#import <math.h>
... rest of code here
NSLog(@"[SW] %i", (int)round(result)); // now prints 44
回答by cichy
Maybe try with *(float)100, sometimes that is the problem ;)
也许尝试使用 *(float)100,有时这就是问题所在;)
回答by vodkhang
I think that your value for todaysCollection
and totalCollectionAvailable
is wrong. Double check for that.
我认为你的价值为todaysCollection
和totalCollectionAvailable
是错误的。仔细检查一下。
Put the NSLog(@"%d", todaysCollection)
right before the if statement
将NSLog(@"%d", todaysCollection)
右边放在if 语句之前