Hello again, I'm slowly getting better, I would never have been able to get this far before, but I'm stuck. Here's what my program is supposed to do:
1. Develop a C++ program that uses a while structure to 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. Your output screen should somewhat look like the following:
Enter the gallons used (-1 to end): 12.8
Enter the miles driven: 287
The miles/gallon for this tank was 22.421875

Enter the gallons used (-1 to end): 10.3
Enter the miles driven: 200
The miles/gallon for this tank was 19.417475

Enter the gallons used (-1 to end): 5
Enter the miles driven: 120
The miles/gallon for this tank was 24.0000

Enter the gallons used (-1 to end): -1

The overall average miles/gallon was 21.601423

Ok here's what I have so far:

#include <iostream>
using namespace std;
int main()
{
int g=0,m=0,a=0;
while(g>-1)
{
cout<<"Enter the gallons used (-1 to end): "<<endl;
cin>>g;
cout<<"Enter the miles driven: "<<endl;
cin>>m;
a=(m/g);
cout<<"The miles per gallon for this tank of gas was: "<<a<<endl;
} 
return 0;

What i'm a bit stuck on:
1.) If a put a decimal in for my gallons used such as: 13.1 the program just starts spitting out information.

2.)If I put in 13 for my gallons used and 200 for my miles driven, my answer should be 15.38461538, but I get just 15. How do I get it to show rounding?
As always, thank you again for all the help.

Dani AI

Generated

Root causes in this thread: the original code used integer types (which drop fractional input and truncate results), tested the sentinel at the wrong time, and never accumulated totals for the overall MPG. The correct pattern is: read gallons first, check the sentinel immediately (so entering -1 stops before requesting miles or doing a division), validate that gallons is positive (avoid division by zero), read miles, compute per-tank MPG, and add miles and gallons to running totals. Use double for numeric data and format output with std::fixed + std::setprecision to match the sample precision.

A robust loop pattern (input validation, sentinel handling, totals accumulation):

#include <iostream>
#include <iomanip>
#include <limits>

int main() {
    double gallons = 0.0, miles = 0.0;
    double totalGallons = 0.0, totalMiles = 0.0;

    while (true) {
        std::cout << "Enter the gallons used (-1 to end): ";
        if (!(std::cin >> gallons)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Invalid number, try again.\n";
            continue;
        }
        if (gallons == -1.0) break;
        if (gallons <= 0.0) { std::cout << "Gallons must be positive.\n"; continue; }

        std::cout << "Enter the miles driven: ";
        if (!(std::cin >> miles)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Invalid number, try again.\n";
            continue;
        }

        double mpg = miles / gallons;
        std::cout << std::fixed << std::setprecision(6)
                  << "The miles/gallon for this tank was " << mpg << "\n";

        totalGallons += gallons;
        totalMiles   += miles;
    }

    if (totalGallons > 0.0)
        std::cout << std::fixed << std::setprecision(6)
                  << "The overall average miles/gallon was " << (totalMiles / totalGallons) << "\n";
    else
        std::cout << "No data entered.\n";

    return 0;
}

Notes: prefer double for better precision; handle nonnumeric input by clearing the stream and discarding the remainder (see ) and format displayed decimals with std::setprecision. As pointed out, integer types will truncate; as recommended, test the sentinel immediately after reading gallons so the program exits cleanly.

Recommended Answers

All 4 Replies

Hello again, I'm slowly getting better, I would never have been able to get this far before, but I'm stuck.

Hi! :) We're all slowly getting better. Nothing is fast when it comes to learning how to code. :)

What i'm a bit stuck on:
1.) If a put a decimal in for my gallons used such as: 13.1 the program just starts spitting out information.

All of your variables are integers. Integers in C++ don't carry a precision, so input with decimals will often choke and output will be truncated.

2.)If I put in 13 for my gallons used and 200 for my miles driven, my answer should be 15.38461538, but I get just 15. How do I get it to show rounding?

This is the same problem. All of your variables are int when they should be float or double. If you have 15.3846 and store it in an int, the precision will be lopped off, leaving you with the whole number 15.

ohhh, I see, lol. That was pretty easy. Thanks for the help. One other question. I'm not sure I really understand a while loop.

#include<iostream>
usingnamespace std;
int main()
{
float g=0,m=0,a=0;
while(g>-1)
{
cout<<"Enter the gallons used (-1 to end): "<<endl;
cin>>g;
cout<<"Enter the miles driven: "<<endl;
cin>>m;
a=(m/g);
cout<<"The miles per gallon for this tank of gas was: "<<a<<endl;
} 
return 0;
}

Where I have while(g>-1) why do I have that and what does that exactly mean? I think that it means while g>-1 the loop will continue to run. If that's the case with my program I need to have a person enter their gas and miles driven a certain number of times then find the average of the total. I'm not paying attention, I understand that you hit -1 to end the program, but why doesn't mine end when you hit -1?

ohhh, I see, lol. That was pretty easy. Thanks for the help. One other question. I'm not sure I really understand a while loop.

#include <iostream>
using namespace std;
int main()
{
float g=0,m=0,a=0;
while(g>-1)
{
cout<<"Enter the gallons used (-1 to end): "<<endl;
cin>>g;
cout<<"Enter the miles driven: "<<endl;
cin>>m;
a=(m/g);
cout<<"The miles per gallon for this tank of gas was: "<<a<<endl;
} 
return 0;
}

Where I have while(g>-1) why do I have that and what does that exactly mean? I think that it means while g>-1 the loop will continue to run. If that's the case with my program I need to have a person enter their gas and miles driven a certain number of times then find the average of the total. So how would that work if it never ends? Thanks again for the all the help.

When you type in -1, the program should end. 0 would be a better value, especially when you are using floating point values. Plus, 0 gallons used is not useful. And if you want it to exit immediately, you have to test the value as soon as it is entered.


And in direct answer to your title:
read Paragraph 5 here
You need to format your code with spacing and indentation

#include <iostream>
using namespace std;
int main()
{    // start indenting -- 4 spaces or so
    float g=0, m=0, a=0;    // space things out
    while (g > -1)
    {
        cout << "Enter the gallons used (-1 to end): " << endl;
        cin >> g;
        cout << "Enter the miles driven: " << endl;
        cin >> m;
        a = (m / g);
        cout << "The miles per gallon for this tank of gas was: " << a << endl;
    } 
    return 0;
}

I'm sorry about the title of my post. Is there anyway that I can change that now? Thanks for the help, next time I'll make sure that my subject title is what my exact problem is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.