Can't get to the right answer

I'm probably stuck starting from line 33rd and up to 37. I have a text file :
5 // How many times went to fill up fuel
7 100 // the first digit is how much liters he filled up and second is how much he drove km.
6 112
12 160
5 80
9 150
and I have to find which car uses least liters per km. So nr_i is the car that uses the least fuel per km. I always end up with answer 1 when it's supposed to be nr_i = 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
//
const char duom [] = "d.txt";
const char rez [] = "r.txt";
//
void EcoVid(int km, int l, int &nr_i, double &vid, int n, int lsum, int kmsum);
//
int main()
{
    ifstream in(duom);
    ofstream out(rez);
    int n, l, km, nr_i, kmsum = 0, lsum = 0;
    double vid;
    in >> n;
    for(int i = 1; i <= n; i++){
        in >> l >> km;
        lsum += l;
        kmsum += km;
        EcoVid(km, l, nr_i, vid, n, lsum, kmsum);
    }
    out << "Geriausias pylimas buvo: " << nr_i << endl;
    out << "Vidutines kuro sanaudos: " << fixed << setprecision(1) << vid << endl;
    return 0;
}
//
void EcoVid(int km, int l, int &nr_i, double &vid, int n, int lsum, int kmsum){
    double km_litrai, best_km_litrai = 9999;
    nr_i = 0;
    vid = 0;
    for(int i = 1; i <= n; i++){
        km_litrai = (double)l / km * 100;
        if(km_litrai < best_km_litrai){
            best_km_litrai = km_litrai;
            nr_i = i;
        }
    }
    vid = (double)lsum / kmsum * 100;
}
Last edited on
Because best_km_litrai is not static, it is reset to 9999 each time the function is called at line 22. Your comparison at line 35 is always against 9999 and therefore always true.
static would fix it. That is a good solution.

the function ecovid is a little strange in design; more commonly the code would have stored the file's values into an array, passed the array to the function, function would find the answer you want all at one go. What you have is not wrong, its just a little unusual (and its a great way to do it when the files are too big to fit in to memory all at once).
Topic archived. No new replies allowed.