Objective-c划分与手动计算不匹配

时间:2014-08-31 02:41:40

标签: objective-c math

现在这是一个奇怪的问题。除法的结果与objective-c和我的手动解决方案不同。显然,我首先认为我的解决方案是错误的,但要么我缺少某些东西,要么......它不是。

以下是代码:

GLfloat t = (gone - delay) / kHyAuthenticationViewControllerAnimationDuration;
NSLog(@"%f %f %f", (gone - delay), kHyAuthenticationViewControllerAnimationDuration, t);

记录0.017853 3.500000 3.035706。这意味着0.017853 / 3.500000应该是3.035706,对吧???错误。它实际上是0.00510085714286。这个数字不会那么小,会产生精确问题,即便如此,它可能会变成像0.0这样的东西......我错过了什么?

使用完整代码编辑:

- (void)animateIn:(NSTimer*)timer
{
    NSArray *buttons = @[self.registrationButton];//, self.facebookButton, self.linkedInButton, self.twitterButton];
    NSDate *when = [timer userInfo];
    NSTimeInterval gone = [[NSDate date] timeIntervalSinceDate:when];
    NSUInteger finished = 0;

    for (int it=0 ; it < [buttons count] ; ++it) {

        UIButton *button = [buttons objectAtIndex:it];
        GLfloat toValue = self.registrationView.frame.origin.y + 37 + button.frame.size.height * it + 10 * it;
        GLfloat fromValue = toValue + self.view.frame.size.height;
        GLfloat delay = kHyAuthenticationViewControllerAnimateInDelayFactor * it;
        CGRect frame;

        // Have we waited enough for this button?
        if (gone >= delay) {

            // Use the timing function
            GLfloat t = (gone - delay) / kHyAuthenticationViewControllerAnimationDuration;
            NSLog(@"%f %f %f", (gone - delay), kHyAuthenticationViewControllerAnimationDuration, t);

//            t = [HyEasing easeOutBounce:t];

            // Is the animation finished for this button?
            if (t >= 1.0f) {
                t = 1.0f;
                ++finished;
                continue;
            }

            // Compute current displacement
            GLfloat displacement = fabs(toValue - fromValue);
            GLfloat y = toValue + displacement * (1.0f - t);

            // Create the frame for the animation
            frame = CGRectMake(button.frame.origin.x, y, button.frame.size.width, button.frame.size.height);
        }

        // Make sure the button is at its initial position
        else frame = CGRectMake(button.frame.origin.x, fromValue, button.frame.size.width, button.frame.size.height);

        [button setFrame:frame];
    }

    if (finished == [buttons count]) {
        [timer invalidate];
    }
}

1 个答案:

答案 0 :(得分:3)

kHyAuthenticationViewControllerAnimationDuration是一个预处理器宏,其复合表达式未括在括号中。因此,当它被合并到另一个复合表达式中时,kHyAuthenticationViewControllerAnimationDuration的术语与包含表达式的术语相互关联,而不是相互关联,从而改变了操作的顺序。

即,

(gone - delay) / kHyAuthenticationViewControllerAnimationDuration

扩展为:

(gone - delay) / 0.5f + 3

评估如下:

((gone - delay) / 0.5f) + 3