0

Conversion from double to int in C

#include<stdio.h> int main(){ double amount; int dollar,cent; scanf("%lf",&amount); dollar=amount; cent=(amount-dollar)*100; printf("%d dollar(s) and %d cent(s)\n",dollar,cent); return 0; } In this program, if I input 12.50; it prints "12 dollar(s) and 50 cent(s)". But if I input 12.01; it prints "12 dollar(s) and 0 cent(s)" instead of "12 dollar(s) and 1 cent(s)". Why is that? Is there any conversion problem between double and int? Or this code is wrong? And, When amount = 12.01; it prints 0 cent(s) When amount = 12.02; it prints 1 cent(s) When amount = 12.03; it prints 2 cent(s) When amount = 12.04; it prints 3 cent(s)... which are wrong. But, When amount = 12.05; it prints 5 cent(s) When amount = 12.06; it prints 6 cent(s) When amount = 12.07; it prints 7 cent(s)... which are correct. I am a beginner so I couldn't solve this issue. Thanks in advance.

21st Apr 2020, 7:19 AM
Kishorè Shanto
1 Réponse
+ 4
When double is converted to int, it is truncated but not rounded. (12.01 - 12)*100 is not equal to one due to limited precision of double (it equals ~ 0.99999...), so the result will be 0. use round function to round result: cent=round((amount-dollar)*100);
21st Apr 2020, 7:46 AM
andriy kan
andriy kan - avatar