2013-10-29 20 views
0

我在Objective-C中有一段代码将秒数(int)转换为形式为“x小时y分钟z秒”的日期字符串。对于8812秒,它应该返回2小时26分52秒,但它返回2小时26分51秒。为什么52.0作为一个浮点数投射为int时变成51?

这是很麻烦的线路:

float timeInSeconds = (60 * ((((seconds/3600.0) - (seconds/3600)) * 60.0) - (int)(((seconds/3600.0) - (seconds/3600)) * 60.0))); 

这导致52.0,如果我NSLog它。但如果我这样做:

int timeInSeconds = (int)(60 * ((((seconds/3600.0) - (seconds/3600)) * 60.0) - (int)(((seconds/3600.0) - (seconds/3600)) * 60.0))); 

我得到51当我NSLog它。为什么这到底?

+3

这实际上不是52.0 - 这是51.99999999 (或一些这样)并被截断。浮点数学的经典问题。 – Floris

+0

那我最好怎么处理呢? –

+1

使用呼叫来回合。 –

回答

5

以下代码的时间间隔,以小时/分/秒 转换而不使用浮点数,因此没有问题四舍五入或 精度损失:

int numberOfSeconds = 8812; // Your value as an example 

int tmp = numberOfSeconds; 
int seconds = tmp % 60; 
tmp /= 60; 
int minutes = tmp % 60; 
tmp /= 60; 
int hours = tmp; 

NSLog(@"%d:%02d:%02d", hours, minutes, seconds); 
// Output: 2:26:52 
相关问题