#include <stdio.h>
int main() {
float initialPrice, discount, VAT, priceWithVAT, priceWithDiscount;
initialPrice = 13.26;
VAT = 0.20;
discount = 0.125;
priceWithVAT = initialPrice * (1.0 + VAT);
priceWithDiscount = priceWithVAT * (1.0 - discount);
printf("Initial Price %10.2f\n", initialPrice);
printf(" + VAT @ %4.1f%% %10.2f\n", VAT * 100, priceWithVAT);
printf(" - discount @ %4.1f%%%10.2f\n", discount * 100, priceWithDiscount);
return 0;
}
I am new to C programming and have been asked to modify the above program so that it uses scanf to read in the initial price before doing the calculations.
What do I need to do?
Thanks
To read a float into the initialPrice
variable, we should first look at how scanf
works. As you can see here, scanf
has the signature:
int scanf(const char *format, ...)
The format
argument is a string that takes a "format string", and you can observe that format strings are more or less comprised of %[chars][type]
where [chars]
is the maximum number of characters that should be read and [type]
is a set of characters representing the type of the argument. In this case, we don't care about the input size and we want to read in a float, so we use the format string %f
. Now we need to provide the address of the variable we want to read into as the next argument, so we use the &
character to get the address of initialPrice
. This is very important because without the &
, the code will cause a segmentation fault. So, our final line looks like
scanf("%f", &initialPrice);
Note that it is a good habit to print some sort of prompt before asking for input, and that you should check the return value of scanf
to make sure it's equal to 1, because that's the amount of variables you want to read into.
This looks like a homework so would be best for you to come up with the solution yourself.
Instead of setting initialPrice to 13.26 add a line of code that calls scanf to set the value of initialPrice to something. scanf will need to be passed some message to the user as well as the initialPrice variable to store whatever the user entered.
printf("Enter the initial price value\\n"); scanf("%f\\n",& InitialPrice); You can edit your by adding this couple of line and don't initialize any value to the "initialPrice = 13.26;" because it will take that value .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.