W.L W.L - 8 days ago 4x
C Question

Handling user's input

when I input a floating point number (eg. 48.3) the result displayed is 48.00 instead of 48.30 and whenever I try to input string with empty space the program ends immediately. I need help, how to fix this problem?

int integer;
char a[50];

float fnum;
char b[50];

printf("Please enter an integer : ");

integer = atoi(a);

printf("\nPlease enter a floating-point number : ");
scanf("%s", &b);

fnum = atoi(b);

printf("Output : \n");

printf("%i + %.2f = %.2f \n", integer,fnum,(integer+fnum));
printf("%i - %.2f = %.2f \n", integer,fnum,(integer-fnum));
printf("%i * %.2f = %.2f \n", integer,fnum,(integer*fnum));


You're convertint string b to an integer by calling atoi. You want to convert it to a floating point number, so use atof:

fnum = atof(b);