I don't get right answer

Write your question here.

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
42
43
44
45
46
47
  #include <iostream>
#include <fstream>

using namespace std;

//
const char duom[] = "duomenys.txt";
const char rez[] = "rezultatai.txt";
//

int main()

{
    int n, l, did, maz, i;
    float viddm;

    viddm = 0;
    did = 0;
    maz = 0;

    ifstream fd(duom);
    ofstream fr(rez);

    fd >> n;

    for (i = 1; i <= n; i++) {

        fd >> l;

        if (l > did)
            did = l;
            else
                maz = l;


    }

    viddm = (did + maz) / 2;

    fr << "Didziausia: " << did << " maziausia: " << maz << " temperaturos vidurkis: " << viddm << endl;

    fd.close();
    fr.close();

    return 0;
}


Ignore the fact that it's not in English. So I find the highest number in the file and lowest which in this case is 11 and 4. Then I get sum of them as you see viddm = (11 + 4) / 2 should be 7.5 but answer which I get is 7. Why ?
Integers automatically truncate. From the compiler's perspective, (did+maz)/2 is an integer operation, as did, maz and 2 are all recognized as int types. This will fix that:
viddm = (did+maz)/2.0;
With the 2 written this way, it is now parsed as a floating point type which won't be truncated.
Topic archived. No new replies allowed.