I'm working on Objective C and I'm trying to deduce the proper index of 2 dimensions array.

To do that I've a few buttons where the tag is setted merging the two index in a single number. In example, a position of 1,1 in the array results on a tag = 11.

After that to unmerge the two components of the index, I'm using following code:

float tag = (float)[sender tag];

    float x = [[NSString stringWithFormat:@"%.2f", tag / 10.f] floatValue];
    //float x = (float)tag / 10.f;

    int y = floor (x);

    int z = (x - y) * 10;

The theory works fine, but I'm surprised when I'm obtaining these results:

tag = 23 x = 2.29999995 instead of expected result of 2.3 (23 / 10 = 2.3 and not 2.2999995)!

I've tried too with double and several operations without success.

Anyone knows what I'm doing wrong?

Thanks.

有帮助吗?

解决方案

Use integer arithmetic. Floating point does not represent all numbers with complete accuracy, especially non-integer values.

Example where [sender tag] is 23:

int senderTag = 23;
int tagA = senderTag / 10;
int tagB = senderTag % 10;
NSLog(@"senderTag: %d, tagA: %d, tagB: %d", senderTag, tagA, tagB);

NSLog output:

senderTag: 23, tagA: 2, tagB: 3

其他提示

Especially, fractions like 1/3, 1/5 can't be represented correctly by floating point arithmetics.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top