how do I get my calculations like ex. I want to add up the average gallons used per mile for a car if the car went like 1450 miles and used 62 gallons of gas

I dont want it to be a whole number i want it to be like 23.38 instead of 23.00

Recommended Answers

All 3 Replies

instead of declaring it as an int, use a float or a double

i decared it as a float and now i want to get the average of gallons per mile for all the 5 cars

#include <iostream>
#include <iomanip>
using namespace std;

struct Car
{
int number, miles;
int gallons;
float averagegallons;
};


int main()
{
        const int NUMCAR = 5;
        int i;
        Car Cars[NUMCAR];
        for(i=0;i<NUMCAR;i++)
        {

cout << "\nPlease enter car number: ";
cin >> Cars[i].number;

cout << "\nPlease enter car miles driven: ";
cin >> Cars[i].miles;

cout << "\nPlease enter car gallons: ";
cin >> Cars[i].gallons;
cin.get();

Cars[i].averagegallons = Cars[i].miles / Cars[i].gallons;
        }

cout << "\n\n              Car Report" << endl;
cout << "        Number        Miles Driven        Gallons Used         Average Per Car" << endl;
        for(i=0;i<NUMCAR;i++)
        {
                cout << setiosflags(ios::showpoint);
                cout << setprecision(2);
                cout << Cars[i].number << "\t" << Cars[i].miles << "\t" << Cars[i].gallons << "\t" << Cars[i].averagegallons
<< endl;

An int divided by an int results in an int using int division.

struct Car
{
int number, miles;
int gallons;
float averagegallons;
};
/* ... */
Cars[i].averagegallons = Cars[i].miles / Cars[i].gallons;

To keep them as ints, cast one of the operands; this will cause the division to be done as floating point.

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.