What am I doing wrong with for loop? - c

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.

Related

I am getting a nan error when doing loops

So, I am using xcode on mac and made a program that basically does simple math with the users entered values and keeps looping unless it is interrupted. At the end of the loop (once it is broken) I want to print out the total average value (so do some more math). I use a counter and sum variables to do this. However, in out output, I am getting a "nan" error when the loop end and the overall average has to display. Can anyone help, please? :/
int main() {
double gallons=0;
double miles=0;
double sum=0;
int count=0;
while (gallons>=0) {
sum+=(miles/gallons);
count++;
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
}
if (gallons<0) {
printf("The average is: %lf", sum/(count-1));
}
return 0;
}
double gallons=0;
double miles=0;
…
sum+=(miles/gallons);
Dividing zero by zero produces a NaN. Once there is a NaN, any arithmetic with it also produces a NaN.
Hm. In first iteration in sum+=(miles/gallons); you try to add to sum value 0/0. So, I think that you need to move this addition after inputs. Something like
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
sum+=(miles/gallons);
count++;

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);
}

C program for bowling game

I need to write a program for a game of bowling. Ask the user to enter the number of games and the number of bowlers. For each bowler, get the score for each game. Display the score. Calculate the average for each bowler and display the average. Finally display the team average.
I wrote a code, it doesn't have errors but the problem is that it doesn't count average score for players and total score for team. Need help with these calculations.
#include <stdio.h>
int main()
{
int playerTotal = 0;
int teamTotal = 0;
int score;
int numgames, player, bowler, game;
printf ("How many games?\n");
scanf ("%d", &numgames);
printf ("How many players?\n");
scanf ("%d", &player);
for (bowler = 1; bowler <= 3; bowler++)
{
for (game = 1; game <= 2; game++)
{
printf ("\nEnter the score for game %d for bowler %d: ", game, bowler);
scanf ("%d", &score);
playerTotal += score;
}
printf ("\nThe average for bowler %d is: ", bowler, playerTotal/2);
printf ("\nThe total for the game is:", teamTotal);
teamTotal += playerTotal;
}
return 0;
}
It's nothing to do with "not counting" - you're just not printing them. This:
printf ("\nThe average for bowler %d is: ", bowler, playerTotal/2);
printf ("\nThe total for the game is:", teamTotal);
should be:
printf ("\nThe average for bowler %d is: %.1f", bowler, playerTotal / 2.0);
printf ("\nThe running team total is: %d", teamTotal);
Note the change from 2 to 2.0, since playerTotal is an int, but if the total is odd then the average will (or should) have a .5 on the end.
You're also going to want to set playerTotal = 0; at the start of your outer for loop, otherwise each player is going to get the scores of all the bowlers who entered their scores previously, which is probably not all that fair of a scoring system. You should change:
for (bowler = 1; bowler <= 3; bowler++)
{
for (game = 1; game <= 2; game++)
{
to:
for (bowler = 1; bowler <= player; ++bowler) {
playerTotal = 0;
for (game = 1; game <= numgames; ++game) {
which will also loop for the same number of times that you had the user enter. If you do this, you'll also need to change:
printf ("\nThe average for bowler %d is: %.1f", bowler, playerTotal / 2.0);
to:
printf ("\nThe average for bowler %d is: %.1f", bowler,
playerTotal / (double) numgames);
to divide your average by the correct number of games.
Other than those things, you made a pretty nice attempt.

Calculate average miles per gallon

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;

Unable to properly terminate "while" loop

I'm trying out programming in C for the first time, and applying it to some concrete stuff...
The program I'm creating with the problem deals with a while loop. The goal of the program is to calculate the average miles per gallon for a set of trucks. I want it to terminate as soon as -1 is inputted as the number of gallons consumed, but instead I have to input it twice, once for the number of gallons, and once for the number of miles. I have found this input to in fact be used as part of the calculation of the result. Here is the code:
#include <stdio.h>
int main()
{
int tanks, miles;
float gallons = 0, average = 0, miles_per_gallon = 0;
tanks = 0;
while (gallons != -1) {
tanks += 1;
miles_per_gallon = (float)miles / gallons;
average = average + miles_per_gallon;
printf("The miles / gallon for this tank was %.3f\n",
miles_per_gallon);
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
average /= tanks;
printf("The overall average miles/gallon was %.3f", average);
return 0;
}
Here is some sample output:
C:\>gallons
Enter the gallons used (-1 to end): 12.3
Enter the miles driven: 700
The miles / gallon for this tank was 56.911
Enter the gallons used (-1 to end): 13.4
Enter the miles driven: 666
The miles / gallon for this tank was 49.701
Enter the gallons used (-1 to end): 17.3
Enter the miles driven: 644
The miles / gallon for this tank was 37.225
Enter the gallons used (-1 to end): 15.5
Enter the miles driven: 777
The miles / gallon for this tank was 50.129
Enter the gallons used (-1 to end): -1
Enter the miles driven: -1
The miles / gallon for this tank was 1.000
The overall average miles/gallon was 38.993
Thanks for any help.
The problem is that the sequence of statements in your code is such that the check for the loop's exit condition is not reached until after the second input is requested. You could add a check for -1 as soon as it's entered, and break out from the loop. Alternatively, you could ask for the miles to be entered ahead of the gallons.
for (;;) { /* This is a "forwver" loop; we break out from the middle */
tanks += 1;
miles_per_gallon = (float)miles / gallons;
average = average + miles_per_gallon;
printf("The miles / gallon for this tank was %.3f\n",
miles_per_gallon);
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
/* This is where you break from the loop: */
if (gallons == -1) return 0;
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
Well you should be able to work it out by yourself, it is easy if you just change your loop or put a if statement after gallons input
while (gallons != -1) {
tanks += 1;
miles_per_gallon = ( float ) miles / gallons;
average = average + miles_per_gallon;
printf("The miles / gallon for this tank was %.3f\n", miles_per_gallon);
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
if(gallons==-1){
printf("Program terminated");
return 0;
}
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
Check for the exit condition after reading gallons. I've made a couple of changes to you code --- because you are only breaking after reading gallons, i've changes the while condition to true. second I changed your test to <=0 as if 0 is entered you divide by 0 which will break your math, and anything less than 0 simply makes no sense. Thirdly I changed the calculation and reporting to after reading the values, so you don't divide by zero
while (1) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
if(gallons <= 0) break;
printf("Enter the miles driven: ");
scanf("%d", &miles);
tanks += 1;
miles_per_gallon = ( float ) miles / gallons;
average = average + miles_per_gallon;
printf("The miles / gallon for this tank was %.3f\n", miles_per_gallon);
}
while (gallons != -1) {
/* snip */
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
Note that you only evaluate the exit criteria after asking both questions. If you want to avoid asking for the miles, you have to contort your loop a little further. It'll look something like this:
while (gallons != -1) {
/* snip */
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
if (gallons == -1)
break; /* exit the while loop */
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
Of course, exiting a loop in the middle like this is a bit rough around the edges, but I don't immediately see a more convenient way to terminate the loop without asking the second question.

Resources