-
if() ?
Code:
#include<iostream>
#include<conio.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
double gallons=0,miles=0,average,tAverage,gSum=0,mSum=0;
do
{
cout<<"\n\nEnter the gallons used(-1 to end input):\t";
cin>>gallons;
cout<<"Enter the miles driven:\t\t\t\t";
cin>>miles;
average=miles/gallons;
cout<<"The miles/gallon for this tank was:\t\t"<<average;
gSum+=gallons;
mSum+=miles;
}
while(gallons!=-1);
cout<<"\nThe total gallons used are:\t\t\t"<<gSum;
cout<<"\nThe total miles driven are:\t\t\t"<<mSum;
tAverage=mSum/gSum;
cout<<"\nThe total average comes out:\t\t\t"<<tAverage;
getch();
}
-----------------------------------------------------end
if() needed?the gallons sum comes 1 less ,same is true for miles.whats wrong in this code?
-
that is because you add -1 to gallons when ending the program.
-
now?
Code:
#include<iostream>
#include<conio.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
double gallons=0,miles=0,average,tAverage,gSum=0,mSum=0;
while(gallons!=-1)
{
cout<<"\n\nEnter the gallons used(-1 to end input):\t";
cin>>gallons;
cout<<"Enter the miles driven:\t\t\t\t";
cin>>miles;
if(gallons!=-1)
{
average=miles/gallons;
cout<<"The miles/gallon for this tank was:\t\t"<<average;
gSum+=gallons;
mSum+=miles;
}
else
cout<<"the end";
}
cout<<"\nThe total gallons used are:\t\t\t"<<gSum;
cout<<"\nThe total miles driven are:\t\t\t"<<mSum;
tAverage=mSum/gSum;
cout<<"\nThe total average comes out:\t\t\t"<<tAverage;
getch();
}
-----------------------------------END
okey now i don't add -1 gallons at the end but it still asks for miles ,I want that the program should end when I enter -1.But it asks for miles at the end and then gives the results.
-
What I would do is to use an infinite loop which exits when the gallons variable is less than 0.
This, of course, must be well documented.
The entry for miles, calculation and display of average would then be skipped when a-1 was entered for gallons.
Unless you need to re-use the averages, I would simply remove the variables, and display the result of the calculation directly.
It might also be better to make gallons and miles as local variables within the loop, if you're using an infinite for loop.
-
That's because your program is doing what you asked it to do logically. You sould check for the exit condition straight after the input for the number of gallons, i.e. move the "if" UP; right after the request for the input of gallons. so that section should look like so:
Code:
cout<<"\n\nEnter the gallons used(-1 to end input):\t";
cin>>gallons;
if(gallons!=-1)
{
cout<<"Enter the miles driven:\t\t\t\t";
cin>>miles;
-
thanku WDT !
Thanku v m WDT.It worked.