浮点数和整数的简单问题

Ste*_*ald 1 iphone math objective-c

一个简单的问题最好用两行代码询问:

CGFloat answer = (abs(-27.460757f) - 9.0f) * (800.0f / (46.0f - 9.0f));
    NSLog(@"According to my calculator, answer should be 399.15, but instead it is: %f", answer);
Run Code Online (Sandbox Code Playgroud)

当我在Xcode中运行它(特别是在iPhone模拟器中)时,我得到:

根据我的计算器,答案应该是399.15,但它是:389.189209

这是因为我对浮标的四舍五入缺乏了解吗?

谢谢!

斯图尔特

小智 5

abs()函数对整数进行操作,因此abs(-27.460757f)返回27.由于您正在使用浮点数,请使用fabsf().