In C and Objective C, if we almost never cast a float or double value to an integer, just using (int)?

I just ran into a situation in Objective-C, where:

NSLog(@"%i", (int) (0.2 * 10));         // prints 2
NSLog(@"%i", (int) ((1.2 - 1) * 10));   // prints 1

so I'm wondering if the value is float or double, and we want an integer, shouldn't we just use it (int)for casting, but use it (int) round(someValue)? Or, to turn the question around, when you just need to use it (int), but in such situations it cannot (int) round(someValue)complete the task, so we should almost always use it (int) round(someValue)?

+5
source share
3 answers

, , . , .

IEEE 754. , , (+1 -1). float - 24- , " " ( " ", ). , 1.25 1.01000000000000000000000. - 53- .

- .1 1.1 . . ".1" "1.1" , , . . .

float int, ( ) ( ). , , , . , .

, , , , , , , . , .5 , "(int) (f +.5)".

+3

, . , int round, .

, , ( , , ), , round. , , ( , ..). , .

: , , :

Macbook Pro:

  • 2,8 Intel Core 2 Duo
  • Mac OS 10.7.4
  • Apple LLVM 3.1
  • -O0 ( )

:

int value;
void test_cast()
{
    clock_t start = clock();
    value = 0;
    for (int i = 0; i < 1000 * 1000; i++)
    {
        value += (int) (((i / 1000.0) - 1.0) * 10.0);
    }

    printf("test_cast: %lu\n", clock() - start);
}

void test_round()
{
    clock_t start = clock();
    value = 0;
    for (int i = 0; i < 1000 * 1000; i++)
    {
        value += round(((i / 1000.0) - 1.0) * 10.0);
    }

    printf("test_round: %lu\n", clock() - start);
}

int main()
{
    test_cast();
    test_round();
}

:

test_cast: 11895
test_round: 14353

. , clock() , , round() .

+1

int .

1.1 → 1, 1.99999999999 → 1, 2.0 → 2

-1.1 → -1, -1.999999999 → -1, -2 → -2

, ? , . , ?

. , , 0.2 * 10 , 2. , , 2. (int) (0.2 * 10) 1 2, " 2" 1.

round (x) is rounded to the nearest integer. Again, if you calculate the round (1.4 + 0.1), the sum of 1.4 and 0.1 is some number very close to 1.5, maybe a little less, maybe a little more, so you don’t know whether it will be rounded to 1.0 or 2.0,

Do you want all numbers from 1.5 to 2.5 to be rounded to 2? Use (int) round (x). You can get a slightly different result if x is 1.5 or 2.5. Perhaps you want to round numbers to 1.9999, but 1.99999999 is rounded to 2. Use double, not float and calculate (int) (x + 0.000001).

0
source

All Articles