S
Shreyas Kulkarni
hi there,
recently i have got a problem regarding calculation of sum of digits in
a floating point or precision number. the weird behaviour of
compiler/language is preventing me from calculating the sum of all
digits. the compiler doesnt store the number as given by the user. some
of the precision digits are lost or changed (at will!). so by any
method, i m unable to reliably calculate the sum of provided number;
except i input the number as a string!
i have tried 2 types of logic -
first i use the intuitive logic of multiplying by 10 and adding the
integer part to the 'sum' in each iteration. all goes well until final
precision digit where this final digit is expanded. e.g. if 0.7 is
remaining, it is expanded to 0.69999999998! why dear, why r u doing
those things that we don want u to do?
/***************************************************/
width=strlen(ltoa((int)a,0,10));
sprintf(str,"%*.*f",width,MAXLEN-width,a);
do{
if(*s=='.') // ignore '.'
continue;
if(!isdigit(*s)) //we have got a char in num, so break away!
break;
else sum+=*s-0x30; //convert to digit from ASCII
}while(*++s);
/***************************************************/
in this case, the sprintf truncates or even expands(reverse of
rounding) long precision numbers.
even the good old gcc is truncating the precision digits at will.
this problem proved to be harder than what i thought initially.
any suggestions?
btw, sorry for this long post, but i m hurt u know? ;-)
TIA
Shreyas Kulkarni
recently i have got a problem regarding calculation of sum of digits in
a floating point or precision number. the weird behaviour of
compiler/language is preventing me from calculating the sum of all
digits. the compiler doesnt store the number as given by the user. some
of the precision digits are lost or changed (at will!). so by any
method, i m unable to reliably calculate the sum of provided number;
except i input the number as a string!
i have tried 2 types of logic -
first i use the intuitive logic of multiplying by 10 and adding the
integer part to the 'sum' in each iteration. all goes well until final
precision digit where this final digit is expanded. e.g. if 0.7 is
remaining, it is expanded to 0.69999999998! why dear, why r u doing
those things that we don want u to do?
/***************************************************/
width=strlen(ltoa((int)a,0,10));
sprintf(str,"%*.*f",width,MAXLEN-width,a);
do{
if(*s=='.') // ignore '.'
continue;
if(!isdigit(*s)) //we have got a char in num, so break away!
break;
else sum+=*s-0x30; //convert to digit from ASCII
}while(*++s);
/***************************************************/
in this case, the sprintf truncates or even expands(reverse of
rounding) long precision numbers.
even the good old gcc is truncating the precision digits at will.
this problem proved to be harder than what i thought initially.
any suggestions?
btw, sorry for this long post, but i m hurt u know? ;-)
TIA
Shreyas Kulkarni