/*Taking input from user to calculate the cost of a travel plan
using the number of travelers/ number of stops/ cost of each stop
giving both the half cost of a trip and its full price*/
int calculate( int total);
#include <stdio.h>
int main(void)
{
float customer, stops, response, cost, i, stop, total, halfcost, totaltrip;
i=0;
printf("Welcome to Airline express.\n");
printf("Would you like to calculate the cost of a trip?");
scanf("%f", &response);
while ( response != 0 )
{
printf("Please enter how many customer will be traveling. Children under 12 are counted as .5:");
scanf("%f", &customer);
if (customer < 0)
customer = 3;
printf("Please enter how many stops there are:");
scanf("%f", &stop);
while (i<stop)
{
printf("Please enter cost of the next stop:");
scanf("%f", &cost);
if (cost < 0)
cost = 100;
total +=cost;
i++;
}
halfcost = calculate(total);
printf("Half cost is: %f", halfcost);
totaltrip = total * customer;
printf("Total cost for trip is: %f\n", totaltrip);
printf("Would you like to calculate another trip?");
scanf("%f", &response);
}
return 0;
}
int calculate( int total)
{
return total/2;
}
I'm having issues with the inputs, I'm trying to make the loop run as the user request another calculations. But when ever it re runs another test it keeps the input of the previous test is there a way to reset the variables to 0?
Ive tried assign all of the variable inside and outside of the loop but I'm kinda lost on what to go from here.
Move the declaration of the variables to sit inside the loop.
while ( response != 0 )
{
float customer = 0, stops = 0, response = 0, cost = 0, i = 0, stop = 0, total = 0, halfcost = 0, totaltrip = 0;
...
}
Related
I need to figure out how to continuously add to the running total of avg mpg and divide by how many times it goes through.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg;
while (miles != -1) {
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg = mpg;
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", avg);
}
}
Okay so I think I got what you are trying to say, so first of all you should initialize avg = 0; and instead of changing avg = mpg; every time the loop runs you should do avg += mpg; so that it will add the previous values to next time the loop runs, Take another int to find the total average, initialize from 0 int t_avg = 0; and for next thing, dividing how many times it goes through you should take a variable and initialize it t = 0; and just increment t every time the loop runs so you will get the time loop goes on and you just have to divide it with avg.
And I would suggest you to use do while loop instead of while so that would be much better.
Hope this is what you were looking for.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg = 0, t = 0,t_avg = 0;
do {
t++;
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg += mpg;
t_avg = avg/t;
// adding average every time and diving every time the loop runs
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", t_avg);
}while(miles != -1);
}
Hello I have been working on a program in C that calculates numbers and it gives me back an average. Now I'm having issues implementing code that will ask a user to enter any number of pairs and calculate the average. Below is the code that I been working on. I'm able to change the while (count < 5)to 10 to get more pairs, but my goal is to ask a user to input any PAIR and THEN calculate the average (re iterating).
#include <stdio.h>
int main () {
int count;
double avg, value, weight, sum, sumw;
count = 0;
sum = 0;
sumw = 0;
avg = 0.0;
while (count < 5) {
printf("Enter value and it's weight:");
scanf("%lf %lf", &value, &weight);
if (weight >= 0) {
sumw = sumw + weight;
sum = sum + value * weight;
count = count + 1;
}
else { printf("weight must be positive\n");
}
}
avg = sum / sumw;
printf("average is %lf\n " , avg );
return 0;
}
**Second part ** On this on I'm not too sure how to make it to PAIRS plus calculate avg. ej: 2 1 , 2 4 , 4 4 etc.
#include<stdio.h>
void main()
{
int i,n,Sum=0,numbers;
float Average;
printf("\nPlease Enter How many pairs do you want?\n");
scanf("%d",&n);
printf("\nPlease Enter the elements one by one\n");
for(i=0;i<n;++i)
{
scanf("%d",&numbers);
Sum = Sum +numbers;
}
Average = Sum/n;
printf("\nAverage of the %d Numbers = %.2f",n, Average);
return 0;
}
but my goal is to ask a user to input any PAIR and THEN calculate the
Well, then you need to store the values somewhere. Recommendation: Have a struct for:
typedef struct
{
double value;
double weight;
} Pair;
Then as soon as you have got number of pairs to read from user, create an array of pairs:
Pair* pairs = malloc(number * sizeof(*pairs));
Very important: Every malloc should go with a free to avoid memory leaks. General recommendation: plan the free immediately when or even before mallocing.
Now inside your loop, you can fill the pairs:
scanf("%lf %lf", &pairs[i].value, &pairs[weight].weight);
Analogously, you can then use the pairs in the array in next loop or for whatever other purpose.
Side note:
if (weight >= 0)
{
// ...
}
else
{
// printf("weight must be positive\n");
}
If user gave negative input, you'll be just skipping some values (or or as in loop proposed, still retain the negative values!).
You might instead read inside a nested loop until value is valid. Additionally consider user providing non-numeric input, too! In that case, you couldn't read a double at all. So general rule is: Always check the result of scanf:
if(scanf("%lf %lf", &value, &weight) != 2 || value < 0 || weight < 0)
// ^
// assuming negative value not desired either
{
// user input was invalid!!!
}
I'm in school learning C. (I am not asking for anyone to write this for me).
Assignment
This program will calculate the miles per gallon MPG for you for three tanks of gas after you have entered the gallons used and miles driven.
I can get my program to start a loop, but I can't figure out how to make it end the loop after 3 runs and give me the Average MPG in 3 tanks. Running the program give me the average, but will keep asking forever.
#include <stdio.h>
int main(void) {
int miles;
float gallons = -1, mg, overall = 0, avg = 0;
while(gallons != 0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
}
return 0;
}
Try this small changes. Use an iterator to get average of 3 tanks.
Modify like
i=0;
while(i < 3) {
i++;
#include <stdio.h>
int main(void) {
int miles, **i=0;**
float gallons = -1, mg, overall = 0, avg = 0;
**while(i < 3)** {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
**i++;**
}
return 0;
}
Sorry: I did not see how is gallons being assigned/initialized in your code, I saw float galons and while (gallons != 0) and then thought that gallons was at some point the result of a computation.
This answer is still useful in my opinion.
Don't use float values to check conditions, floats are not accurate because their machine representation cannot be, so gallons != 0 will probably hardly ever be true, use int instead and your loop control will work correctly. Only use float for the average value.
But in fact, because your specific problem can be solved with a for loop, you should use
for (int i = 0 ; i < 3 ; ++i)
instead, that way you know that it will only loop 3 times.
SIDE NOTE: learn more about scanf() and why you MUST check the value that it retuns in programs like yours.
Your program, as written, does not stop at 3 tanks. It will continuously ask for tanks until you answer 0 to the number of gallons used.
To make it read at most three tanks, replace while (gallons != 0) with for (int i = 0; i < 3; i++). That will make the main loop run three times only.
But then it won't print the overall average. It will simply quit after running three times. The code that shows the overall average is inside that if test that checks if you typed 0 gallons. Remove that if test and move the printf statement which shows the overall average near the end of the program, right before the return statement. This way it will run after the for loop runs 3 times.
float gallons = -1;
It doesn't make any sense;
And you need to notice one thing that is
while(gallons!=0){
//code
}
You are asking the user to enter the value if gallons to input and your not changing it's value so this value will always be true in while and loop will go infinite.
If you need to run the loop three times then you can do it by using variable.
`
int i=3;
while(i>0){//code
i--;
}
Here I have edited your program ;
#include <stdio.h>
int main(void) {
int miles,i=3;
float gallons, mg, overall = 0, avg = 0;
while(i>0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;i--;
}
return 0;
}
`
I am trying to create a C program which calculates the monthly payment and print a table of payment schedule for a fixed rate loan. My issue is that the loop only iterates once but I cannot figure out why. Here is how the output should looked like:
#include <stdio.h>
#include <math.h>
double calculatePayments(double loan, double rate, int payment);
int main(){
double loan,rate,monthly,principal,interest,balance;
int payment, counter;
counter = 0;
balance = 0.0;
printf("Enter amount of loan: ");
scanf("%lf", &loan);
printf("Enter interest rate per year:%% ");
scanf("%lf", &rate);
printf("Enter number of payments: ");
scanf("%d", &payment);
monthly = calculatePayments(loan, rate, payment);
printf("Monthly payment should be %.2f\n", monthly);
printf("—————AMORTIZATION SCHEDULE—————\n ");
printf("N\tPayment\tPrincipal\tInterest\tBalance\n ");
do{
rate = rate/12/100;
interest = loan * rate;
principal = monthly - interest;
balance = loan - principal;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance < 0);
return 0;
}
double calculatePayments(double loan, double rate, int payment) {
rate = rate/12/100;
double mul = pow(1+rate, payment);
return (loan * mul * rate) / (mul - 1);
}
Changing up the do ... while loop
// e.g. 7.5/12/100 = 0.00625
rate = rate/12/100;
do{
// e.g. 500*0.00625=3.125
interest = loan * rate;
// e.g. 101.88-3.125=98.76
principal = monthly - interest;
// e.g. 500-98.76=401.24
balance = loan - principal;
// update loan
loan = balance;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance > principal);
Balance would never be < 0. That is why you loop is only running once. If you had done a while loop instead of do while it wouldn't run at all.
Change balance < 0 to balance > 0
You are checking to loop only if balance is less than Zero.
but at the first iteration the value of balance would be 401$ (not < 0)
So breaking.
You should be checking for balance > 0 in while
Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}