C language > Beginner questions

round function ?

(1/1)

Ivenko72:
v 10.00.6


--- Code: ---#include <stdio.h>
#include <math.h>

int main(void)
{
    char buf[1000];
    int i;
    for (i = 0; i < 1000; i++)
    {
        buf[i] = 0;
    }
    sprintf(buf, "%f", round(0.5));
    printf(buf);
    return 0;
}

--- End code ---

round(0.5)==0
round(1.5)==2

John Z:
Good catch.  Welcome to the forum!

same with v 9.00.9 btw.

roundf and roundl exhibit the same behavior.

takes a=0.500000000000001; to be 'correct' and meet "rounding halfway cases away from zero, regardless of the current rounding direction" for the specific case of exactly 0.500000000000000

Could be related to a few other precision related math discrepancies already reported in the Bug section.

John Z

Ivenko72:
In the loop, of course, buf[ i ] = 0
I pasted the source text using the clipboard, but for some reason the [ i ] (without spaces) disappeared ...

John Z:
Yes.  The entire loop serves no purpose anyway. The sprintf will write the string starting at the address of the variable and then append a 0 on the end so clearing the string in this case does not change or help anything.
For the future, where the string or buffer must be cleared, memset can be more efficient.

John Z

frankie:

--- Quote from: Ivenko72 on October 16, 2020, 08:57:26 PM ---In the loop, of course, buf[ i ] = 0
I pasted the source text using the clipboard, but for some reason the [ i ] (without spaces) disappeared ...

--- End quote ---
When posting code enclose it in

--- Code: ---[code]
[ /code]  //Space inserted to show the end code slash

--- End code ---

Navigation

[0] Message Index

Go to full version