"Curley Q." <cu*****@bogus.net> a écrit dans le message de

news:40**************@bogus.net...

Curley Q. wrote: Is there a std lib rounding function that will round a real to a given

number of decimal places? Something like:

double round_it(double number, int decimal_digits)

pass 34.5678, 3 to it and it returns 34.568

Here is my solution manipulating the double as a string:

/* round n to ndigits decimal digits */

char* round_it(char *n, int ndigits)

{

int int_digits, point;

for(int_digits = 0; point != '.'; ++int_digits)

point = n[int_digits];

if(n[int_digits + ndigits] >= '5')

++n[int_digits + (ndigits - 1)];

n[int_digits + ndigits] = '\0';

return n;

}

There are some problems with your solution.

Suppose you receive:

round("12.1",5);

You will index beyond the string you are getting

and touching memory you do not own. You assume that

there is a digit at the position of the point + "ndigits".

Another serious problem is that you just increase the

digit before the end alphabetically!!

If you had '9' you will get ':' as the result of your addition.

You do not carry over the digits. '9' should be transformed

into '0' and the same operation should be repeated until

there are no more digits in the whole string. This is called

"carry propagation".

In a more cosmetic way, you could use strchr to eliminate the

loop since you are just looking for a point. You do

char *p = strchr(n,'.');

if (p == NULL)

return n;

int_digits = p - n;

The termination clause of your "for" loop is just that the pointer

points to something different than the '.' char. If you receive

a string without a point you start an infinite loop since the terminating

zero will be ignored (it *is* different than '.') and you will go on

scanning beyond the end of the string with bad consequences:

either a crash or ending in a random fashion when you hit

some byte that has the value of '.'

Using strchr avoids that problem and is maybe faster. strchr

doesn't read beyond the end of the string, respecting the

terminating zero.

But for strings that contain a point, and have more

digits than the specified precision your function will

work. Of course if we do not hit the 9 in the previous

position. :-)