2011-11-28 74 views
3

我使用的标准方程距离/速度=到达时间。这工作正常,但答案是一个浮点数,大多数人会觉得1.75小时转换为1小时45分钟很尴尬。将代表小时的浮点数转换为整数小时和分钟

我想获取最终的浮点数结果,并将小时数从分钟中分别提取为整数。

这里是我试过:

-(IBAction)calculate:(id)sender { 

float spd=[speed.text floatValue]; 

float dist=[distKnots.text floatValue]; 

//this give me the answer as a float 

float arr=(dist/bs); 

//this is how I showed it as an answer 

//Here I need to convert "arr" and extract the hours & minutes as whole integers 

arrivalTime.text=[NSString stringWithFormat:@"%0.02f", arr]; 

[speed resignFirstResponder]; 
} 

这是我试图做转换 - 在纸上它的工作原理,但在代码是完全错误的:

int justHours = arr*60; 

int justMinutes = (arr*60)-(justHours*60); 

//then for the user friendly answer: 

arrivalTime.text=[NSString stringWithFormat:@"%n hours and %n minutes", justHours, justMinutes]; 

我是Objective-C的新手,希望有一种方法可以解决这个问题,或者采用更好的方法解决这个问题。

+0

您应该接受或不接受答案 – lexeme

回答

0

int justHours = arr/60;似乎不正确,应该是int justHours = arr;

3

arr变量以小时已测量,所以你不应该缩放,只是舍去了下去:

int justHours = (int)arr; 

,然后你分钟六十次原之间的(整数)的区别圆整小时(即小数部分)。

int justMinutes = (int)((arr - justHours) * 60); 
+0

'int justHours = arr;'*截断*不四舍五入。 – progrmr

+0

是的,这在技术上是正确的 - 趋于零 – Alnitak

+0

谢谢,我知道我搞砸了假设(太晚了),我已经把它拿出来了。我从答案中得到的数学到目前为止是正确的,但问题是将浮点数转换为整数而不会出现错误......我是否正确地做了这个部分?或者如果不是需要做什么? – Rob

0

检查NSNumber numberFormater类。我相信你可以用时间格式来包装你的float并把它返回给用户。

相关问题