目标c countOfBytesReceived over countOfBytesExpectedToReceive返回0.000000

时间:2018-03-01 16:21:51

标签: ios objective-c integer-division

我正在尝试countOfBytesReceived / countOfBytesExpectedToReceive,但它会返回0.0000001.000000

我在NSLogcountOfBytesReceived上都做了countOfBytesExpectedToReceive我可以看到countOfBytesExpectedToReceive保持与预期相同且countOfBytesReceived更改。

CGFloat progressRatio = [task countOfBytesReceived] / [task countOfBytesExpectedToReceive];

[progressView setProgress:progressRatio];

NSLog(@"%lld", [task countOfBytesReceived]);
NSLog(@"%lld", [task countOfBytesExpectedToReceive]);
NSLog(@"%f)", progressRatio);

progressRatio总是会返回0.0000001.000000

我将此代码放在scheduledTimerWithTimeInterval中,因此每隔0.01运行一次。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

这是因为progressRatio是根据两个整数值计算的。在C中,当你分割两个整数时,你得到一个整数。那是。添加一个转换来获得一个浮动:

CGFloat progressRatio = (CGFloat) [task countOfBytesReceived] / (CGFloat )[task countOfBytesExpectedToReceive];

答案 1 :(得分:1)

countOfBytesRecievedcountOfBytesExpectedToReceive都是64位整数。 C表达式求值将二进制表达式的左或右参数提升为最兼容的类型。

(int64_t)a / (int64_t)b

但由于此表达式的两边都是64位整数,因此不需要转换,它会执行整数数学运算。鉴于这些值的性质,结果将是0(如果a< b)或1(如果a == b)。

然后

C评估下一个表达式:

(float)ratio = (int64_t)n

由于这是一项赋值,因此必须将整数(10)转换为浮点值(1.00.0)。

如果要执行浮点除法,请强制C将原始整数转换为浮点值 first

CGFloat progressRatio = (CGFloat)[task countOfBytesReceived] / (CGFloat)[task countOfBytesExpectedToReceive];