Calculate average miles per gallon - c

Are there any C language programmers on here that can help me figure this out?
I am having trouble getting the calculation for the average miles per gallon to work and my head is spinning. I would really appreciate if anyone have a solution ^_^
int x, number_of_tanks = 3;
double total_num1, total_num2;
double total_miles_per_gallon;
float division, avg;
float num1, num2;
for (x = 1; x <= 3; x++)
{
printf("Enter the number of gallons used for tank #%i: ",x);
scanf("%f", &num1);
fflush(stdin); /* clear input buffer */
printf("Enter the number of miles driven: ");
scanf("%f", &num2);
fflush(stdin); /* clear input buffer */
/*--------------------------------------------------------------*/
/* calculate and output the miles per gallon from user input. */
/* ------------------------------------------------------------ */
division = num2 / (float) num1;
printf("The miles per gallon for this tank %.1f divided by %.1f is %.1f", \
num2, num1, division);
total_num2 = total_num2 + num2;
printf("The total of miles is %f\n", total_num2);
total_num1 = total_num1 + num1;
printf("The total of gallons is %f\n", total_num1);
}
avg = (double) total_num2 / total_num1;
printf("Overall average miles per gallon for three tanks: %.1f", avg);

You don't initialise your totals, so they are undefined. When you start adding to them, you get undefined results. I bet that's what you mean by it not working.
Do this:
double total_num1 = 0;
double total_num2 = 0;

Related

What am I doing wrong with for loop?

Please help. I am supposed to Calculate 3 MPG for 3 tanks. I am able to do it without using a loop. However, I am supposed to use a for-loop to replace one section of code. I think I have the proper code but I just don't know if I placing it correctly.
So, instead of writing "Enter the number of miles driven", 3 times, it's supposed to be replaced by for (miles = 1; miles <=3; miles = miles+1) {
miles = miles + 0;. IS this right? I asked my professor do we use counters, or nested loops, and I was told no. What am I doing wrong?
#include <stdio.h>
int main (void)
{
/*Variable Delclarations*/
/*----------------------*/
float gallons = 0;
float miles = 0;
float mpg = 0;
float avg = 0;
printf ("\nEnter the number of gallons used in tank #1: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1) {
miles = miles + 0;
printf ("Enter the number of miles driven: ");
}
scanf ("%f/n", &miles);
printf ("/nThe miles per gallon for this tank is: %.1f\n miles per gallon",
(float)miles/gallons);
printf("\n\n"); /* new line */
printf ("Enter the number of gallons used in tank #2: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1)
miles = miles + 0;
printf ("Enter the number of miles driven: ");
scanf ("%f/n", &miles);
printf ("The miles per gallon for this tank is: %.1f\n", (float)miles/gallons);
printf("\n\n"); /* new line */
printf ("/nEnter the number of gallons used in tank #3: ");
scanf ("%f/n", &gallons);
for (miles = 1; miles <=3; miles = miles+1)
miles = miles + 0;
printf ("Enter the number of miles driven: ");
scanf ("%f/n", &miles);
printf ("The miles per gallon for this tank is: %.1f\n", (float)miles/gallons);
printf("\n\n"); /* new line */
printf ("Your overall average miles per gallon for three tanks is %.1f\n")
scanf ("%f/n", &avg);
}
So in this case there is no need for three separate loops, everything can be handled in one. What you're trying to do in this exercise is get three separate inputs for your tanks. these inputs can be gathered using the scanf command. For each loop your gallons and miles variable should be assigned to a value of 0;
this would result in the following code for the inside of the loop:
miles = 0;
gallons = 0;
printf ("Enter the number of gallons used in tank #%i: ", tank);
scanf ("%f", &gallons);
printf ("Enter the number of miles driven: ");
scanf ("%f", &miles);
printf ("The miles per gallon for this tank is: %.1f miles per gallon", (float)(miles / gallons));
avg += (miles / gallons);
printf("\n\n");
you can add the result of miles / gallons onto average and at the end divide this by the total amount of tanks.
If you do all of this you should end up with something that looks like this:
#include <stdio.h>
int main (void)
{
float gallons = 0;
float miles = 0;
float avg = 0;
int tank_amount = 3;
for (int tank = 1; tank <= tank_amount; tank++) {
miles = 0;
gallons = 0;
printf ("Enter the number of gallons used in tank #%i: ", tank);
scanf ("%f", &gallons);
printf ("Enter the number of miles driven: ");
scanf ("%f", &miles);
printf ("The miles per gallon for this tank is: %.1f miles per gallon", (float)(miles / gallons));
avg += (miles / gallons);
printf("\n\n");
}
printf ("Your overall average miles per gallon for three tanks is %.1f\n", (avg / tank_amount));
}
Also be sure to indent your code in a nice and readable way and use {} brackets for your loops, this makes it a lot easier to read, which also helps if u need to debug it :)
You have three for() loops. The first one contains two statements: a print statement that will therefore be printed three times, and "miles = miles + 0", which does exactly nothing. The other two for loops (since they don't have braces) include only one statement, the same "miles = miles + 0", which does nothing.
Always use braces with your loops, and make sure that whatever you want to happen multiple times is inside the braces. And indent your code so that you can see at a glance what's inside and outside. Finally, if you use a variable like "miles" in the for() statement, don't also modify it inside the loop.

uninitialized local variable used in C language

so i have been at this for a bit and i am a little stumped i am getting "uninitialized local variable gallons used". in my take_Input function on conversion(gallons);
i am aware that that means that the value for gallons is not being recognized.
why is the gallons to liters function not placing a value for gallons so that the conversion function has that value. any help appreciated thanks...
code:
double take_Input(void)
{
double a, b, c, d;
double gallons;
printf("please enter how many liters of A: ");
scanf("%lf", &a);
printf("please enter how many gallons of B: ");
scanf("%lf", &b);
printf("please enter how many liters of C: ");
scanf("%lf", &c);
printf("please enter how many gallons of D: ");
scanf("%lf", &d);
gallons_To_Liters(a,b,c,d);
conversions(gallons);
return(0);
}
double gallons_To_Liters(double a, double b, double c,double d)
{
double gallons, liters;
liters = a + c;
gallons = b + d;
gallons = (liters * 3.79) + gallons;
return(0);
}
double conversions(double gallons)
{
double totalGallons = gallons;
double quarts = totalGallons * 4;
double pints = totalGallons * 8;
double cups = totalGallons * 16;
double fluid_ounces = totalGallons * 128;
double tablespoons = totalGallons * 256;
double teaspoons = totalGallons * 768;
// output statements.
printf("the amount of gallons is: %.2f \n", totalGallons);
printf("the amount of quarts is: %.2f \n", quarts);
printf("the amount of pints is: %.2f \n", pints);
printf("the amount of cups is: %.2f \n", cups);
printf("the amount of fluid ounces is: %.2f \n", fluid_ounces);
printf("the amount of tablespoons is: %.2f \n", tablespoons);
printf("the amount of teaspoons is: %.2f \n", teaspoons);
return (0);
}
Your gallons_To_Liters function sets the local variable gallons, but does nothing with it. You need to return this value from the function.
Then in the calling function, you need to assign the return value of gallons_To_Liters to the gallons variable in that function.
double take_Input(void)
{
....
gallons = gallons_To_Liters(a,b,c,d);
....
}
double gallons_To_Liters(double a, double b, double c,double d)
{
double gallons, liters;
liters = a + c;
gallons = b + d;
gallons = (liters * 3.79) + gallons;
return gallons;
}
You need to keep in mind that variables in different functions are distinct from each other, even if their names are the same.
Also, for the take_Input and conversion functions, their return values are not used for anything, so change the functions to have a return type of void and remove the return statements from those functions.

How To Use Decimals Of An Integer

I would like overpay to display overpay as the total amount paid if the result was not rounded. calculateMonths must be an integer which makes this much more difficult. I tried using
double dblCalculateMonths = (double)calculateMonths(principal, annualInterestRate, monthlyPayment);
but it did not work properly. I am not sure how to fix this problem while keeping calculateMonths as an integer. Help would be very much appreciated!
I would like the results to look like this:
** Welcome to the CPSC 1010-S3 Payment Calculator **
Enter the principal amount: 5000.00
Enter the annual interest rate (in %): 15.0
Enter the monthly payment: 100.00
Calculating...
Total # of months needed to pay off: 79
App roximate # of years needed to pay off: 6.6
Total interest paid: $2900.00
Total amount paid: $7900.00
You overpaid: $4.43
But the last line displays as
You overpaid: $100.00
I am not sure how to change this. My list of code is below
#include <stdio.h>
#include <math.h>
int calculateMonths(double principal,double annualInterestRate,double monthlyPayment)
{
double x = ((log(monthlyPayment)-log(monthlyPayment-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
return x;
}
int main()
{
double principal, annualInterestRate, monthlyPayment;
printf("** Welcome to the Payment Calculator **\n\n");
printf("Enter the principal amount:\t\t\t");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in%%):\t\t");
scanf("%lf", &annualInterestRate);
printf("Enter the monthly payment:\t\t\t");
scanf("%lf", &monthlyPayment);
printf("\nCalculating...\n\n");
double roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment)+1;
printf("Total # of months needed to pay off:\t\t %.0f\n", roundedMonths);
double years = roundedMonths/12;
printf("Approcimate # of years needed to pay off: \t %.1f\n", years);
double amountPaid = roundedMonths * monthlyPayment;
double interestPaid = amountPaid-principal;
printf("Total interest paid:\t\t\t\t $%.2f\n", interestPaid);
printf("Total amount paid:\t\t\t\t $%.2f\n", amountPaid);
double dblCalculateMonths = (double)calculateMonths(principal, annualInterestRate, monthlyPayment);
double overpay = amountPaid - dblCalculateMonths*monthlyPayment;
printf("You overpaid:\t\t\t\t $%.2f\n", overpay);
printf("%f", dblCalculateMonths);
printf("\n\n");
return(0);
}
what's the logic in keeping calculateMonths() an integer? make it a double and it should work.
double calculateMonths(double principal,double annualInterestRate,double monthlyPayment)
and make roundedMonths an integer. Also you could add 0.5 to have the right round.
int roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment)+0.5;
printf("Total # of months needed to pay off:\t\t %d\n", roundedMonths);
LE: Try this:
int calculateMonths(double principal,double annualInterestRate,double monthlyPayment, double *dblCalculateMonths)
{
*dblCalculateMonths = ((log(monthlyPayment)-log(monthlyPayment-annualInterestRate/1200.0*principal))/log(annualInterestRate/1200.0+1.0));
return *dblCalculateMonths;
}
int main()
{
double principal, annualInterestRate, monthlyPayment, dblCalculateMonths;
printf("** Welcome to the Payment Calculator **\n\n");
printf("Enter the principal amount:\t\t\t");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in%%):\t\t");
scanf("%lf", &annualInterestRate);
printf("Enter the monthly payment:\t\t\t");
scanf("%lf", &monthlyPayment);
printf("\nCalculating...\n\n");
double roundedMonths = calculateMonths(principal, annualInterestRate, monthlyPayment, &dblCalculateMonths)+1;
printf("Total # of months needed to pay off:\t\t %.0f\n", roundedMonths);
double years = roundedMonths/12;
printf("Approcimate # of years needed to pay off: \t %.1f\n", years);
double amountPaid = roundedMonths * monthlyPayment;
double interestPaid = amountPaid-principal;
printf("Total interest paid:\t\t\t\t $%.2f\n", interestPaid);
printf("Total amount paid:\t\t\t\t $%.2f\n", amountPaid);
double overpay = amountPaid - dblCalculateMonths*monthlyPayment;
printf("You overpaid:\t\t\t\t $%.2f\n", overpay);
printf("%f", dblCalculateMonths);
printf("\n\n");
return(0);
}

Convert a float to an int

I have a price for a car, let's say 10000. I want to apply a 20% sale to this price.
I have a struct in which auta->cena is a float.
int year, i, n=0, pocet=1, sale;
scanf(" %d", &year);
scanf(" %d", &sale);
for(i=1; i<=pocet; i++){
if(year == auta->rok){
++n;
pocet++;
auta->cena *= ((float)(100 - sale) / 100); //calculate price after 20% sale
//temp = ((int)(temp * 100 + 0.5)) / 100.0; //use this formula to round up final price, it doesnt work, I get 0.00
printf("%.2f\n", auta->cena);
}
auta = auta->dalsi;
}
I am not good at converting—can anyone explain it to me, please? How should I go about it?
If you're going to print the value with %.2f, you don't have to do any rounding. But if you want to round the value internally, the following will work. I'm printing it with %.5f to show that the value is really changed.
#include <stdio.h>
int main() {
int discount;
double price;
printf("Enter a price: ");
scanf(" %lf", &price);
printf("Enter a percentage discount: ");
scanf(" %d", &discount);
price *= (100.0 - discount) / 100; // calculate price after discount
printf("after discount: %.5f\n", price);
price = (int)(100 * price + 0.5) / 100.0;
printf("rounded: %.5f\n", price);
}
I'm using double above to preserve enough precision to demonstrate that the calculation works with, for example, a price of 10000 and a discount of 20. If you do it with float, you lose enough precision that there's no point in rounding to the nearest cent. The internal value will be imprecise anyway.
Here is a variant of the same code using float:
#include <stdio.h>
int main() {
int discount;
float price;
printf("Enter a price: ");
scanf(" %f", &price);
printf("Enter a percentage discount: ");
scanf(" %d", &discount);
price *= (100.0 - discount) / 100; // calculate price after discount
printf("after discount: %.5f\n", price);
price = (int)(100 * price + 0.5) / 100.0;
printf("rounded up: %.5f\n", price);
return 0;
}

Can someone point out a small logic error to me?

I am doing the following program out of a book and don't understand where I am going wrong with it. Can someone please point out to me some mistake in logic that I am missing?
Develop a program that will input the miles driven and gallons used for each tankful.
The program should calculate and display the miles per gallon obtained for each tankful. After processing all input information, the program should calculate and print the combined miles per gallon obtained for all tankfuls.
#include <stdio.h>
int main(void) {
int total = 0, count = 0;
float gallons_used, mpg, miles;
while(gallons_used != -1) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
total /= count;
printf("Average miles to the gallon was: %d\n", total);
return 0;
}
Now, It appears that I have the loop just right, up until the point I exit it with the value of -1 because it still asks for the mileage of that tank, and obviously inputting it completely throws off the total at the end.
You can use an infinite loop and break it just in case gallons_used = -1
for(;;) { // <-- infinite loop
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
if (gallons_used == -1)
break; // <-- exit the loop
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
while(true) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
printf("Enter the miles driven: ");
scanf("%f", &miles);
if(gallons_used== -1 )break;
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
#include <stdio.h>
int main(void) {
int total = 0, count = 0;
float gallons_used, mpg, miles;
while(gallons_used != -1) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
if (gallons_used < 0) // check gallons_used
break;
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
total /= count;
printf("Average miles to the gallon was: %d\n", total);
return 0;
}
You are using gallons_used uninitialized. Using uninitialized variables invokes undefined behavior. You need to initialize it first before comparing it in while's conditional expression. You can do this as
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used); // Reading value for gallons_used
while(gallons_used != -1) {
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
}

Resources