Let's say I have 3 cars right. And I'm using for loop. I need to find which car uses least fuel for most driven distance. And I just don't know how to make it that in for loop if car uses less fuel and drives most driven distance it would say that first, second or third. I tried to do like best = i; But it doesn't assign to the correct i. I know it's hard to explain....
Example
1st car - Uses 30l fuel and drives 100km
2nd car - 30l 120km
3rd car - 30l 80km
It would make sense that the 2nd is the answer but in my for loop i doesn't assign to the 2nd car.
1 2 3 4 5 6
for (i = 1; i <= n; i++) { // The n is how many cars were tested
cout << "Type " << i << " Car used fuel and driven distance: \n";
cout << "Fuel: "; cin >> fuel;
cout << "Distance: "; cin >> distance;
}
And basicly I have no idea how to continue it so it would assign and check if the previous car was better or not. All I know that is my if should be something like
if (fuel < ??? (don't know what to type) && distance > (don't know what to type as well)
Create a double best_km_per_litre and an int best_i. You can initialise both as 0.
As you go through the loop, calculate km_per_litre for that car. If it is bigger than best_km_per_litre then update the latter to the new value and update best_i to i. If it is not bigger then you don't have to update. At any time you are comparing with all previous cars, not just the immediately preceding one.
After finishing looping just print out best_km_per_litre (best fuel efficiency) and best_i (number of best car).
That's it, unless multiple cars have the same "best fuel efficiency", in which case you would have to store car details in an array and traverse it twice.
Please put your code in code tags (the first item, <>, on the formatting menu to the right.
Please ensure that it is the whole code, and is properly indented and formatted: no missing braces, or braces in the wrong place. Also, remove variables that you don't use (sanaudos and atstumas).
You are correctly updating best_i. You need to update best_km_per_litre at the same point.
Make this change and then let's see the code again. Remember those code tags!
Experiment with n different cars. Everyone in the empty tank was charged with a certain amount of fuel after the car drove until the fuel stalled. Type each cars fuel consumption and mileage of each car.
I think I needed to use while loop ? because "The car drove until the fuel stalled".
No, a for loop is fine. Do NOT use a while loop here.
Please make the changes I have just suggested.
(Sorry, the system crashed out as I was posting - had to retype it twice).