0

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

Jay
  • 11
  • 1
  • 5
    Don't use doubles for currency – user234461 Mar 31 '16 at 15:17
  • 1
    It'll be easier to help if we see how all the variables involved are declared. – blazs Mar 31 '16 at 15:19
  • 2
    Seriously, don't use doubles for currency. I know it's not what you asked but it's best practice is to use the minor unit with an integer type, or use a dedicated data type to represent currency. Floating point numbers are good for representing a large range of numbers that don't need to be particularly accurate. Using them for currency forces you to propagate rounding error checks and explicit rounding throughout your codebase. – jvalli Mar 31 '16 at 15:23
  • Possible duplicate of [Problems with scanf and doubles](https://stackoverflow.com/questions/19890748/problems-with-scanf-and-doubles) – phuclv Sep 09 '18 at 04:38

4 Answers4

5

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.

ReflexiveCode
  • 256
  • 3
  • 7
2

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.

user234461
  • 1,133
  • 12
  • 29
1

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

0

Since you defined your variable as double you should use:

scanf("%lf", &userpayment);

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

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64