I have a simple section of a "money" program which needs to validate the user input and print a rounded float value (to a unit of 10, but must have 2 decimal places) and I was only able to successfully buffer out: char, char mixed with float, negative floats but not float mixed with char (this always extracts out the float and prints it) instead of treating the whole input as wrong. Below is the code:
#include <stdio.h>
int main(void)
{
double amount; /* Input: how much a customer paid */
int error; /* Flag: indicate if an error has happened during input */
int status; /* Number of successful inputs processed by scanf */
/* Get a amount due (repeat input if invalid) */
do {
error = 0;
printf("Enter amount due: ");
status = scanf("%lf", &amount);
/* if input was not number (probably character(s)) */
if (status != 1) {
error = 1;
printf(" Incorrect input! Enter again.\n");
while ((getchar()) != '\n'); /* remove input */
}
/* input was an integer, but it was outside the valid range */
else if (amount < 0) {
error = 1;
printf(" Amount must be positive! Enter again.\n");
}
} while (error);
printf("The amount due is %0.1f0\n", amount);
return(0);
}
E.g: Output:
Enter amount due: fh32
Incorrect input! Enter again.
Enter amount due: -221.35
Amount must be positive! Enter again.
Enter amount due: 78.57ehwj
The amount due is 78.60
And is there a proper programming way (probably) to round off to a unit of 10, but must have 2 decimal places?
for example below code...
printf("Enter amount due: ");
status = scanf("%lf", &amount);
--------
printf("The amount due is %.1f0\n", amount);
...is designed to round off to one decimal place, then 'add' a zero but it only gives correct results sometimes:
Output:
Enter amount due: 35.56
The amount due is 35.60
Enter amount due: 35.55
The amount due is 35.50 [wrong]
Enter amount due: 35.25
The amount due is 35.20 [wrong]