减去定义为常量的两个浮点数时出现意外结果

时间:2013-08-24 19:37:19

标签: objective-c floating-point

我正在尝试调整帧数。我有两个常量定义为浮点数 - viewTotalHeightExpandedviewTotalHeight。我正在减去两个以获得differenceY

  CGFloat differenceY = viewTotalHeightExpanded - viewTotalHeight;
  NSLog(@"viewTotalHeightExpanded = %f", viewTotalHeightExpanded);
  NSLog(@"viewTotalHeight = %f", viewTotalHeight);
  NSLog(@"differenceY = %f", differenceY);

日志显示:

2013-08-24 12:30:48.305 WS[25737:c07] viewTotalHeightExpanded = 406.000000
2013-08-24 12:30:48.305 WS[25737:c07] viewTotalHeight = 366.000000
2013-08-24 12:30:48.306 WS[25737:c07] differenceY = 680.000000

为什么differenceY不是40?

修改

这是定义viewTotalHeightviewTotalHeightExpanded的方式:

#define likeBarHeight 20.0f
#define viewTotalHeight likeBarY+likeBarHeight+sortBarHeight

所有其他链式常量(例如likeBarYsortBarHeight)都定义为与likeBarHeight类似的浮点数。

1 个答案:

答案 0 :(得分:5)

这就是你正在做的事情:

CGFloat differenceY = viewTotalHeightExpanded - viewTotalHeight;

因为viewTotalHeight像likeBarY + likeBarHeight + sortBarHeight转换为

CGFloat differenceY = viewTotalHeightExpanded -likeBarY+likeBarHeight+sortBarHeight

所以试试这个:

 CGFloat differenceY = (viewTotalHeightExpanded) - (viewTotalHeight);

或者甚至可以更好地使viewTotalHeight在没有括号的情况下重复使用

#define viewTotalHeight (likeBarY+likeBarHeight+sortBarHeight)