I need help, kind of lost and my book isnt helping.

The problem is: A car with a 20-gallon gas tank averages 23.5 miles per gallon when driven in town, 28.9 miles when driven on highway. Write a program that calculates and displays the distance the car can travel on one tank of gas when driven in town and when driven on the highway.

I tried to figure this out but i just keep getting multiple errors when i try to run it.


#include <iostream>
using namespace std;

int main()
{
int tank, town, highway;

tank = 20;
town = 23.5;
highway = 28.9;
cout << "A car has a " << tank << " gallon gas tank. \n";
cout << "It averages " << town << " miles per gallon while in town. \n";
cout << "It averages " << highway << " miles per gallon on the highway. \n";

distance = town * tank
distance = highway * tank
return 0;
}
im about to find out.
@ JSwizzy

Let's take a look at your code. Shall we?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
    int tank, town, highway; 

    tank = 20;
    town = 23.5;
    highway = 28.9;
    cout << "A car has a " << tank << " gallon gas tank. \n";
    cout << "It averages " << town << " miles per gallon while in town. \n";
    cout << "It averages " << highway << " miles per gallon on the highway. \n";

    distance = town * tank 
    distance = highway * tank
	   return 0;
}


Take a look at line 6: You declared the variables as int. However, when you declared them on line 9 and line 10, you define them as double.
For example, in the variable town, the number 23.5 will be truncated to 23. The same with highway variable will be truncated from 28.9 to 28
The reason is that you declared those variables as int and not a double or float. If you change it from int to double, you will get better
calculations.
Take a look at line 15. You did not declare the variable distance. In other words, what type of variable distance is? Is it an integer, float, double?
You are missing a semicolon on line 15 and line 16.
You are using the same variable "distance" to perform two different calculations (1. town * tank, 2. highway * tank). I would use two different variables
to obtain the results of those calculations.
Last edited on
Okay i changed it and tried to run it again and I got 3 errors.
Line 8, 9, and 10
double tank = 20;
double town = 23.5;
double highway = 28.9;

errors all say: error C2086: 'double tank' : redefinition
@ chicofeo
Last edited on
oh wow thanks guys that worked.
Topic archived. No new replies allowed.