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.
This should give you 107 as a result