我试图找出countOfBytesReceived / countOfBytesExpectedToReceive
,但要么返回0.000000
或1.000000
。
我在NSLog
和countOfBytesReceived
做了一个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.000000
或1.000000
,当它不应该。
我在scheduledTimerWithTimeInterval
中有这个代码所以它确实每0.01运行一次。
我究竟做错了什么?
这是因为progressRatio是根据两个整数值计算的。在C中,当你分割两个整数时,你得到一个整数。那是。添加一个转换来获得一个浮动:
CGFloat progressRatio = (CGFloat) [task countOfBytesReceived] / (CGFloat )[task countOfBytesExpectedToReceive];
countOfBytesRecieved
和countOfBytesExpectedToReceive
都是64位整数。 C表达式评估将二进制表达式的左或右参数提升为最兼容的类型。
(int64_t)a / (int64_t)b
但由于此表达式的两边都是64位整数,因此不需要进行转换,它会执行整数数学运算。鉴于这些值的性质,结果将是0
(如果a <b)或1
(如果a == b)。
然后C计算下一个表达式:
(float)ratio = (int64_t)n
由于这是一个赋值,它必须将整数(1
或0
)转换为浮点值(1.0
或0.0
)。
如果要执行浮点除法,请强制C首先将原始整数转换为浮点值:
CGFloat progressRatio = (CGFloat)[task countOfBytesReceived] / (CGFloat)[task countOfBytesExpectedToReceive];