简体   繁体   中英

BEDMAS precedence in (Obj-)C?

I've just solved a rather weird problem I've been having in an iOS Application. I need to apply a scaling factor (which I have calculated to be 64/38 ~= 1.684 ), to a value passed into a method.

The crux of my problem looks like this:

- (void)applyScaleTo:(int)value {

    // value := 64
    int first = value * (64/38)
    NSLog(@"First: %d", first);
    int second = (64 * value)/38;
    NSLog(@"Second: %d", second);

}

The desired value is 107 , but the logs look like this:

First: 64
Second: 107

My solution is to use the second method, which is fine, but my question is, why this discrepancy? (Incidentally, if first is changed to a float , it still logs as 64.00000... .)

In the first case you divide two integers (64 and 38) which give you an integer value back (1). To correct that you don't have to change the result value to a float (this will merely convert your integer result of 64 to a float), but at least one of your operants of the division.

int first = value * ( (float) 64 / 38)

This should give you 107 as a result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM