NO

Author Topic: round function ?  (Read 2363 times)

Offline Ivenko72

  • Member
  • *
  • Posts: 2
round function ?
« on: October 16, 2020, 08:35:38 AM »
v 10.00.6

Code: [Select]
#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;
}

round(0.5)==0
round(1.5)==2
« Last Edit: October 17, 2020, 10:42:17 AM by frankie »

Offline John Z

  • Member
  • *
  • Posts: 860
Re: round function ?
« Reply #1 on: October 16, 2020, 01:29:31 PM »
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

Offline Ivenko72

  • Member
  • *
  • Posts: 2
Re: round function ?
« Reply #2 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 ...
« Last Edit: October 16, 2020, 08:59:48 PM by Ivenko72 »

Offline John Z

  • Member
  • *
  • Posts: 860
Re: round function ?
« Reply #3 on: October 16, 2020, 09:43:25 PM »
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

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: round function ?
« Reply #4 on: October 17, 2020, 10:45:00 AM »
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 ...
When posting code enclose it in
Code: [Select]
[code]
[ /code]  //Space inserted to show the end code slash
« Last Edit: October 17, 2020, 10:48:12 AM by frankie »
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide