Jay
Jay

Reputation: 11

scanf doesn't read double

I got problems regarding the minus operation in c.

printf("\nPlease enter your payment:\n", userpayment);
scanf("%.2f", &userpayment);

customerchange = userpayment - totalfinal;
printf("The amount of change is %.2f\n", customerchange);

I declared userpayment and totalfinal as double.

Whenever I input the price for example; userpayment = 2000 and the totalfinal is 1500, the output will always be 1500. What is the solution to this?

This is the output:

Enter the Price of Item: 500 Enter Quantity of Item: 3 The total amount of Payment is: RM1500.00 Is this the last item? y Rm50 cash rebate has been given to the customer. Total Payment before cash rebate is: 1500 Total Payment after cash rebate is 1450

Please enter your payment: 5000 Your change is RM-14500.00

Upvotes: 0

Views: 502

Answers (4)

Since you defined your variable as double you should use:

scanf("%lf", &userpayment);

The f is for float values, lf (long float) for doubles.

Upvotes: 0

Rick R
Rick R

Reputation: 256

If "userpayment" is defined as a double, then change

scanf("%.2f", &userpayment);

to

scanf("%lf", &userpayment);

or change your variables to floats instead.

As it stands, you're scanning a float into the memory of a double, resulting in unpredictable behavior.

Upvotes: 5

You are confusing the format from printf, it is similar but not the same, try just replacing %.2f to %lf

Upvotes: 1

user234461
user234461

Reputation: 1205

You have an incorrect format specifier in scanf. Read the documentation.

http://www.cplusplus.com/reference/cstdio/scanf/

You should also check the return value of scanf to ensure that it was able to parse what you expected it to parse.

Also, if you had read your compiler warnings you could have saved yourself the trouble of asking this question.

Upvotes: 2

Related Questions