I used n = 100.0*n; float roundf(float n); to covert dollar to cent and round it. However when I use gdb with an input of 4.2, the converted n is 419.999... and the program yields a result of 22 instead of 18. Why my round doesn't work?
float roundf(float n) is declaration of round function, and here I want to just use it. So I should type float rounded = roundf(n);
You need to round it after multiplying it by 100. And I'd suggest using round()
rather than roundf()
. You don't want a float for your number of cents. You want to be dealing in integers.`
-
I indeed round it after multiplication, and per the man round command, round() is for double type of variables. How can I round n and covert it to an integer? – eifphysics Jan 16 '15 at 13:14
-
-
multiplying by 100 doesn't work. I have tested that. On multiplying by 100, the float input 4.1 will turn to 410 cents and 0.5 will turn into 50 cents. 0.5 & 0.50 are different.. – Prateek Pande Jan 17 '15 at 13:40
-
4.1 should be 410. and .5 should be 50 when multiplied by 100. What is the issue? – curiouskiwi♦ Jan 17 '15 at 23:47