Ok so I'm trying to build a basic program to calculate the price of a pizza order. I want it to ask if the customer is done ordering. If they enter y then I want the loop to continue, if any other character entered I want it to stop. When I enter any character the program just continuously prints out all my printf statements. I am using codeblocks. Here is my code. I get 2 warnings.
warning: initialization makes integer from pointer without a cast [enabled by default] at line 17 where i declare the keepgoing variable.
warning: comparison between pointer and integer [enabled by default]|
at line 19 where the while loop starts.
#include <stdio.h>
#include <stdlib.h>
main()
{
#define LARGEPIZZAPRICE
#define SMALLPIZZAPRICE
#define LARGEPIZZATOPPING
#define SMALLPIZZATOPPING
#define DRINK
int numberOfLargePizzas;
int numberOfSmallPizzas;
int numberOfLargeToppings;
int numberOfSmallToppings;
int numberOfDrinks;
int keepGoing = "y";
while (keepGoing == "y")
{
printf("How many large pizza's do you want\n");
scanf(" %d", &numberOfLargePizzas);
printf("How many large toppings do you want\n");
scanf(" %d", &numberOfLargeToppings);
printf("How many small pizza's do you want\n");
scanf(" %d", &numberOfSmallPizzas);
printf("How many small toppings do you want\n");
scanf(" %d", &numberOfSmallToppings);
printf("Would you like to order more. Enter a y or n\n");
scanf(" %i", &keepGoing);
}
}`
*****UPDATE*****
Ok thanks for all the help, it's running good now. If somebody can look at it and give any tips to tighten it up or do what i'm doing easier, please let me know. This is learning experience for me and I'm doing it through trial and error. The program runs but I have a feeling I'm structuring it wrong. Here's what I have:
#include <stdio.h>
#include <stdlib.h>
main()
{
#define LARGEPIZZAPRICE 12
#define SMALLPIZZAPRICE 10
#define LARGEPIZZATOPPING 2
#define SMALLPIZZATOPPING 1.50
#define DRINK 1.50
#define TAXRATE .05
int numberOfLargePizzas;
int numberOfSmallPizzas;
int numberOfLargeToppings;
int numberOfSmallToppings;
int numberOfDrinks;
char keepGoing ='y';
float largePizzaTotal;
float smallPizzaTotal;
float drinkTotal;
while (keepGoing == 'y')
{
printf("How many large pizza's do you want\n");
scanf(" %d", &numberOfLargePizzas);
if(numberOfLargePizzas != 0){
printf("How many large toppings do you want\n");
scanf(" %d", &numberOfLargeToppings);
}
printf("How many small pizza's do you want\n");
scanf(" %d", &numberOfSmallPizzas);
if(numberOfSmallPizzas !=0){
printf("How many small toppings do you want\n");
scanf(" %d", &numberOfSmallToppings);
}
printf("How many drinks would you like\n");
scanf(" %int", &numberOfDrinks);
printf("Would you like to order more. Enter a y or n\n");
scanf(" %c", &keepGoing);
}
largePizzaTotal = (LARGEPIZZAPRICE*numberOfLargePizzas)+(LARGEPIZZATOPPING*numberOfLargeToppings);
smallPizzaTotal=(SMALLPIZZAPRICE*numberOfSmallPizzas)+(SMALLPIZZATOPPING*numberOfSmallToppings);
drinkTotal = DRINK*numberOfDrinks;
printf("Subtotal: %2f", largePizzaTotal + smallPizzaTotal + drinkTotal);
}
You can't compare strings that way in c, probably you meant
char keepGoing = 'y';
if (keepGoing == 'y')
but then you should fix the scanf() too
scanf(" %c", &keepGoing);
The
int keepGoing = "y";
compiles well if you have compiler warnings disabled, but it's wrong.
Your compiler is indeed telling you that it's wrong, because int and pointer are incompatible types.
You are comparing an integer variable with character data.
Replace int keepGoing = "y";
with
char keepGoing = 'y';
and replace
while (keepGoing == "y")
with while (keepGoing == 'y')
or if you want to take care of cases, replace it with
while ( keepGoing == 'y' || keepGoing == 'Y')
You asked for tips to tighten up what you are doing. I took a bit of time and outlined an approach to your pizza shop that surrounds a Pizza Shop Menu. Rather than prompting for how many of each -- during every loop, this just presents a small menu where you choose L for large, S for small and D for drink, and then fill in the quantity. (menu entries can be either upper or lower case) Invalid menu selections are not allowed (no error is shown, the menu just redisplays)
Rather than waiting to sum and total at the end, I find it easier to simply keep a running total of each type sold, the subtotal, tax, etc.. You can compare both methods and see which you prefer.
Also, after each scanf input (where the format string does not consume the newline), the input buffer is emptied to prevent scanf from appearing to skip over entries. Take a look and let me know if you have questions. There are many, many ways to do this, none more right than the next (as long as they are correct). It all comes down to format taste and efficiencies at that point. (note: no additional header files were included in case that is a limitation, so there are easier ways to check for a valid entry with strchr, etc.. using string.h, etc.)
#include <stdio.h>
#include <stdlib.h>
/* defines are preprocessor commands that simply cause the
* preprocessor to do a global search-and-replace of the
* labels with values. They traditionally go at the top.
* You can add storage type suffixes to the numbers to
* prevent ambiguity. (e.g. F float, U unsigned, ...)
*/
#define LARGEPIZZAPRICE 12.0F
#define SMALLPIZZAPRICE 10.0F
#define LARGEPIZZATOPPING 2.0F
#define SMALLPIZZATOPPING 1.50F
#define DRINK 1.50F
#define TAXRATE .05F
/* empty input buffer after reading from stdin */
void flush_stdin ()
{
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
int show_menu ()
{
int c = 0;
/* quick & dirty menu */
printf ("\n Pizza Shop Menu\n\n");
printf (" L) Large Pizza\n");
printf (" S) Small Pizza\n");
printf (" D) Drink\n");
printf (" --------------------\n");
printf (" C) Checkout\n\n");
printf (" Choice: ");
c = getchar ();
flush_stdin ();
/* return only upper case letters */
return c > 'Z' ? c - 'a' + 'A' : c;
}
int main (void)
{
/* ALWAYS INITIALIZE ALL VARIABLES
* accidentally reading from an uninitialized variable
* is Undefined Behavior.
*/
int numberOfLargePizzas = 0;
int numberOfSmallPizzas = 0;
int numberOfLargeToppings = 0;
int numberOfSmallToppings = 0;
int numberOfDrinks = 0;
float price = 0.0;
float subtotal = 0.0;
float tax = 0.0;
while (1)
{
int n = 0;
switch (show_menu())
{
case 'L' :
printf ("\n How many large pizza's do you want : ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfLargePizzas += n;
price = n * LARGEPIZZAPRICE;
tax += price * TAXRATE;
subtotal += price;
n = 0;
printf (" How many large toppings do you want: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfLargeToppings += n;
price = n * LARGEPIZZATOPPING;
tax += price * TAXRATE;
subtotal += price;
}
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'S' :
printf ("\n How many small pizza's do you want : ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfSmallPizzas += n;
price = n * SMALLPIZZAPRICE;
tax += price * TAXRATE;
subtotal += price;
n = 0;
printf (" How many small toppings do you want: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfSmallToppings += n;
price = n * SMALLPIZZATOPPING;
tax += price * TAXRATE;
subtotal += price;
}
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'D' :
printf ("\n How many drinks would you like: ");
scanf ("%d", &n);
flush_stdin ();
if (n)
{
numberOfDrinks += n;
price = n * DRINK;
tax += price * TAXRATE;
subtotal += price;
}
printf ("\n Subtotal : %.2f\n Tax : %.2f\n Total : %.2f\n",
subtotal, tax, subtotal + tax);
break;
case 'C' :
printf ("\nOrder:\n");
printf (" ------------------------\n");
printf (" Large Pizzas : %2d\n Large Toppings : %2d\n", numberOfLargePizzas, numberOfLargeToppings);
printf (" Small Pizzas : %2d\n Small Toppings : %2d\n", numberOfSmallPizzas, numberOfSmallToppings);
printf (" Drinks : %2d\n", numberOfDrinks );
printf (" ------------------------\n");
printf (" Subtotal : %6.2f\n Tax : %6.2f\n Total : %6.2f\n",
subtotal, tax, subtotal + tax);
printf (" ------------------------\n\n");
return 0;
default:
/* uncomment to show bad menu entry */
// printf (" <--invalid entry-->\n");
break;
}
}
return 0;
}
Example:
$ ./bin/pizzas
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: l
How many large pizza's do you want : 2
How many large toppings do you want: 2
Subtotal : 28.00
Tax : 1.40
Total : 29.40
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: d
How many drinks would you like: 4
Subtotal : 34.00
Tax : 1.70
Total : 35.70
Pizza Shop Menu
L) Large Pizza
S) Small Pizza
D) Drink
--------------------
C) Checkout
Choice: c
Order:
------------------------
Large Pizzas : 2
Large Toppings : 2
Small Pizzas : 0
Small Toppings : 0
Drinks : 4
------------------------
Subtotal : 34.00
Tax : 1.70
Total : 35.70
------------------------
Related
I need to write a program where users can input their numbers as much as many as they defined, then the program will try to find which one is the lowest value and the highest value. The problems I face are:
When the program executed, the second line will wait on user's input (number) before the printf
The error "system" seems unreliable, sometimes works, sometimes doesn't work
The program only checks the last number entry, therefore it only shows the last number in min and max
You may give hints or corrections along the answers. Thank you very much.
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",×);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Output:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00
Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect.
How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.
#include <stdio.h>
float max(float num1, float num2){
if(num1 > num2){
return num1;
}
return num2;
}
float min(float num1, float num2){
if(num1 < num2){
return num1;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",×);
printf("Type in the number: ");
scanf("%f", &data_Input);
// the first number will be minimum and maximum
mini = data_Input;
maxi = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
// make it a composite if condition
while(data_Input<0 || data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(maxi, data_Input);
mini= min(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",×);
for(interval=1; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Solving the printf issue is easy. As stdout is line buffered (at least by default - it can be changed) it is flushed whenever a newline is inserted in the buffer. So, just add a newline after each message print, for example
printf("How many number would you like to type in ? : \n");
and you'll be fine.
Talking about the wrong calculation of min and max, your attempt has basically two big issues:
You are not acquiring times inputs, but only one. In fact, every time you call scanf you overwrite the same variable data_Input without performing any comparison with the previous inputs
You call min() and max() function only once, after the last input. Furthermore you try to compare the argument with a local variable that has local storage and a lifetime limited to the function itself so that at the next call it will be initialized again
In order to have a variable inside a function that it is initialized only the first time you can use static keyword. But it is not I suggest you to solve the issue.
In my opinion you don't need comparison functions: you can just update maxi and mini each time you get a new input (solving both the aforementioned issues at once):
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : \n");
scanf("%d",×);
printf("Type in the number: ");
scanf("%f", &data_Input);
maxi = data_Input;
mini = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: \n");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
/* Check input and, in case, update max and min */
if(data_Input > maxi)
maxi = data_Input;
if(data_Input < mini)
mini = data_Input;
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The comparison is performed inside the loop, so you don't need to store the inputs into an array.
You have plenty issues in your code.
Functions min & max do not make any sense
You do not check result of the scanf and you do not know if it was successfull
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int times, interval;
float mini, maxi, data_Input;
do
{
printf("\nHow many number would you like to type in ? : ");
}while(scanf(" %d\n",×) != 1);
for(interval = 0; interval < times; interval++)
{
do
{
printf("\nType in the number: ");
}while(scanf(" %f",&data_Input) != 1 && (data_Input < 0 || data_Input > 100));
printf("%f\n", data_Input);
maxi = interval == 0 ? data_Input : MAX(maxi, data_Input);
mini = interval == 0 ? data_Input : MIN(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
When the program executed, the second line will wait on user's input (number) before the printf
Drop "\n" from "%d\n". It blocks until non-white space detected after the number and is not needed.
printf("How many number would you like to type in ? : ");
// scanf("%d\n",×);
scanf("%d",×);
printf("Type in the number: ");
If output still not seen when expected, flush it. Typically printing a '\n' will flush stdout, but not certainly.
printf("How many number would you like to type in ? : ");
fflush(stdout); // add
The error "system" seems unreliable, sometimes works, sometimes doesn't work
At least this issue: sequential check vs. checking both conditions together input validity.
Rather than
while(data_Input<0){
...
}
while(data_Input>100){
...
}
Test together.
while(data_Input<0 || data_Input>100){
...
}
The program only checks the last number entry, therefore it only shows the last number in min and max
True as code only compares values once with one call to max(). That function only compares the number to 0 rather than prior values. Likewise for min().
Consider an algorithm change
// Pseudo code for max
prompt How many number would you like to type in ? : "
get times
max_value = -INF // set to minimum possible float
for each value 1 to times
prompt "Type in the number: "
get data_Input
if data_Input > max_value
max_value = data_Input
print max_value
I am still new to C programming and I am having a bit of a problem in my coding. I am aware that I can't just ask for help without trying to fix it by myself first, so I tried fixing it and is still having the same problem.
My problem is, my coding displayed an incorrect calculation like below.
ORDER PRICE SUMMARY
===========================================
Customer No. Total Order Price(RM)
===========================================
1 RM 40.00
2 RM 40.00
3 RM 478664371470163710000000000000000.00
===========================================
Grand Total RM 478664371470163710000000000000000.00
===========================================
Customer 1 and 2 showed the correct price but it just got messed up for Customer 3, which affects the grand total.
My coding is below, and it is obvious that I am using the simplest way of writing my code since my goal is to just answer a coding question.
#include <stdio.h>
float calculatePrice(char);
void main()
{
char comboType, addon;
int comboQty, addonQty,i=1,j=1;
float orderPrice = 0.00, comboPrice, addonPrice, grandPrice=0.00; // new float
float customerPayment[3], allPrice[3]; // declare array
printf ("--------------------------------------------------------------\n");
printf (" ~ SATAY RESTAURANT ~ \n");
printf ("--------------------------------------------------------------\n");
printf (" Combo Type Item Price (RM) \n");
printf ("--------------------------------------------------------------\n");
printf (" A 25 Chicken Stay + 25 Beef Satay 40.00\n");
printf (" B 30 Chicken Stay + 20 Mutton Satay 52.00\n");
printf (" C 10 Mutton Stay + 40 Beef Satay 46.00\n");
printf (" Add-On 1 Ketupat 0.60\n");
printf ("--------------------------------------------------------------\n");
for (j=0;j<3;j++)
{
printf("\n Customer %d\n",j+1);
printf("-------------");
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
while (comboType != 'X' && comboType != 'x') // start while loop
{
comboPrice = calculatePrice (comboType);
printf(" Order Price for Combo %c : RM%.2f \n ", comboType, comboPrice);
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
allPrice[j] += comboPrice;
}
printf("\n Add-On Ketupat (Y/N) : "); // if X, ask for add-on
scanf(" %c", &addon);
if (addon != 'N' && addon != 'n')
{
printf(" Enter Ketupat Quantity : ");
scanf("%d", &addonQty);
addonPrice = 0.60 * addonQty;
allPrice[j] += addonPrice;
printf(" Order price for Ketupat : RM%.2f\n",addonPrice);
}
printf("\n Total Order Price for Customer %d : RM%.2f\n\n",j+1, allPrice[j]);
customerPayment[j] = allPrice[j];
}
printf("\n\n\n\t ORDER PRICE SUMMARY ");
printf("\n===========================================");
printf("\n Customer No. Total Order Price(RM)");
printf("\n===========================================");
for (i = 0; i<3; i++)
{
printf("\n %d RM %.2f",i+1,customerPayment[i]);
grandPrice += customerPayment[i];
}
printf("\n===========================================");
printf("\n Grand Total RM %.2f",grandPrice);
printf("\n===========================================");
getch ();
}
float calculatePrice (char comboType)
{
float comboPrice, allPrice = 0.00;
int comboQty;
printf(" Enter Quantity : ");
scanf("%d", &comboQty);
if (comboType == 'A' || comboType == 'a')
{
comboPrice = 40.00 * comboQty;
}
if (comboType == 'B' || comboType == 'b')
{
comboPrice = 52.00 * comboQty;
}
if (comboType == 'C' || comboType == 'c')
{
comboPrice = 46.00 * comboQty;
}
return comboPrice;
}
It would be greatly appreciated if someone could help detecting my mistake.
At the beginning , you do not fill allPrice array with zeros, so you add to it what was left from memory.
Just at the start of your main, add allPrice[3] = {0, 0, 0}; and customerPayment[3] = {0, 0, 0};
Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}
I've been stumped for the past few days trying to modify my current code to be able to input an undetermined number of students.
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
for (students = 0; students < 5; students++)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
}
return 0;
}
As it is now, I have to manually input the amount of students. Does anyone know how I can modify this code in order to enter an undetermined amount of students? I'm starting to think that it is impossible to do and maintain the integrity of the rest of the code. Any help is greatly appreciated, thanks!
You can do something like while (stillAdding) instead of the for loop, and prompt the user with Enter student name or QUIT to stop, or even Would you like to enter a new student [Y/n]. You'd modify the stillAdding variable accordingly. In short, you leave it up to the user to specify when they want to stop inputting more data.
You can ask for the number of users before the for and then use that number as upper bounds of the for. Something like this:
int students, exams, nr;
printf("Enter Student Number \n");
scanf("%d", &nr);
for (students = 0; students < nr; students++)
{
//your code
}
You can ask the user whether there are more students per loop:
#include <stdio.h>
int main(void)
{
char StudentName[100];
float ExamValue, Sum, Avg;
int students, exams;
char stop;
for (;;)
{
Sum = 0.0;
printf("Enter Student Name \n");
scanf(" %s", StudentName);
for (exams = 0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum / 3.0;
printf("Average for %s is %f\n", StudentName, Avg);
puts("More students?(Y/N)");
scanf("%*[^yYnN]%c%*[^\n]%*c", &stop); // read one of 'y', 'Y', 'n', 'N', then discard that line, including '\n'.
if (stop == 'N' || stop == 'n')
break;
}
return 0;
}
You can prompt the user to supply the number of inputs. Once the user tells you how many inputs will be given, then you can simply use a for loop to read that many inputs
This is a program that asks the user to input Shipping information about selling bikes, pretty lame. At the end when it prints out the number of bikes order, and the total cost, the numbers get screwed up. The previously entered amounts seem to be sticking in the memory. How do I fix this? If that is not the problem I would not mind being told so :)
#include <stdio.h>
#include <math.h>
//structure
typedef struct
{char cust_name[25];
char add_one[20];
char add_two[20];
}ORDER;
ORDER order;
int main(void){
fflush(stdin);
system ( "clear" );
//initialize variables
double number_ordered = 0;
double price;
char bike;
char risky;
double m = 359.95;
double s = 279.95;
//inputs for order
printf("Enter Customer Information\n");
printf("Customer Name: ");
scanf(" %[^\n]s", &order.cust_name);
printf("\nEnter Street Address: ");
scanf(" %[^\n]s", &order.add_one);
printf("\nEnter City, State, and ZIP: ");
scanf(" %[^\n]s", &order.add_two);
printf("\nHow Many Bicycles Are Ordered: ");
scanf(" %d", &number_ordered);
printf("\nWhat Type Of Bike Is Ordered\n M Mountain Bike \n S Street Bike");
printf("\nChoose One (M or S): ");
scanf(" %c", &bike);
printf("\nIs The Customer Risky (Y/N): ");
scanf(" %c", &risky);
system ( "clear" );
//print order
printf("\n**********Shipping Instructions**********");
printf("\nTo: %s\n %s\n %s", order.cust_name, order.add_one, order.add_two);
if (bike == 'M' || bike == 'm')
printf("\n\nShip: %d Mountain Bikes", number_ordered);
else
printf("\n\nShip: %d Street Bikes", number_ordered);
if (bike == 'M' || bike == 'm')
price = number_ordered * m;
else
price = number_ordered * s;
if (risky == 'Y' || risky == 'y')
printf("\nBy Freight, COD %d\n", price);
else
printf("\nBy Freight, And Bill The Customer %d\n", price);
printf("*****************************************\n");
return 0;
}
You are printing number_ordered and price, which are doubles, using %d. %d is only for integer types. Use %lf to printf or scanf doubles.
The formats for both your scanf and your printf are wrong, so you're neither reading nor writing your values properly.