I am trying to do a programm that will ask the user to enter how many items they are buying after they enter how many items they are buying i want them to input each price, i think i have that so far. then i want to add each item to give tehm a total of their purchases but i dont know how to do it, and also i dont know why i have to use this for, someone was helping me previous so i dont know what that means. thanks again
#include%26lt;stdio.h%26gt;
main()
{
int i, items;
float sum, item_price, total;
char dummy;
printf("How many items are you buying today? ");
scanf("%i", %26amp;items);
for (i = 0; i %26lt; items; i++)
{
printf("Enter the price?");
scanf("%f",%26amp;item_price);
sum += item_price;
}
scanf("%c", %26amp;dummy);
}
C program help me plz?
//we need this line in order to be able to use the input and output
//functions (printf, scanf)
#include %26lt;stdio.h%26gt;
main()
{
//here, we declare the variables we want to use later on
int i, items;
float sum, item_price, total;
char dummy;
//add \n for a newline after the text
printf("how many items are you buying today?\n");
//%d means, that a decimal integer will be read from the commandline
scanf("%d", %26amp;items);
//because you only ever add to sum, you have to initialize it to zero
// so the program knows what the value should be before anything is added
sum = 0;
for(i=0; i %26lt; items; i++)
{
//more \n for more fun in life (actually only more linebreaks)
printf("\nEnter the price?\n");
scanf("%f", %26amp;item_price);
sum += item_price;
}
//here you should probably tell the customer how much he has to pay
printf("\n final sum: %f\n", sum);
//this is probably so the program will wait for a keystroke before
//quitting
scanf("%c", %26amp;dummy);
}
Reply:Get rid of the last scanf() because you are done. You only need to print the sum (use printf() -- look up how to format the data)
Can I make a suggestion? You really need to comment your code with your design before you start cutting the code. For example, right before the printf("How many ....), put
/*from the user, get the number of items*/
Before the loop, put
/* for the number of times indicated by items, get the price of each item */
then after the scanf
/*compute the total price for all items */
If you had done something like that, you would have known that you are done and the only thing left to do is print out the total.
FYI: All code-toads want to jump in and start coding. The good ones design first. It saves LOTS of time and headaches.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment