Friday, July 31, 2009

C Programming: How can I count Decimal Places!?

My program uses scanf to take the value of a floating number. The problem is, I want it to also tell how many decimal points there were in the number.





For example, let's say someone inputs in 2.34. I want my program to know that there are 2 decimal places, as well as store the value of 2.34 as some variable.





Any bright ideas?

C Programming: How can I count Decimal Places!?
I would use sprintf() to convert it from a float to a string and then search the string for the decimal and count the digits after it.
Reply:1. First, convert your floating point number into integer. i.e. 2.34 --%26gt; to 2.





2. Subtract the integer from the floating point number. i.e. 2.34-2=0.34.





3. Multiply the difference by 10. ==%26gt; 0.34*10=3.4 parallely increment the counter say i=1.





4. Go to the step one. Repeat until the difference turns out to be zero.
Reply:convert to string,


subtract the location of the decimal point in the string from the length of the string


No comments:

Post a Comment