ParanoidParrot
ParanoidParrot

Reputation: 41

C++ Input/output

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int a , b , c , i , n;
    int d = 0;
 ifstream myfile;
 myfile.open("Duomenys1.txt");
 myfile >> n;
 for (int i = 0; i < n; i++ )
 {
     myfile >> a >> b >> c;
     d +=  (a + b + c)/3 ;
 }
ofstream myotherfile;
myotherfile.open ("Rezultatai1.txt");
myotherfile << d;
myotherfile.close();
myotherfile.close();
return 0;
}

The programs should read 3 (3 is n) rows of numbers (5 7 4 ; 9 9 8; 8 7 8), rows are summed up separately and given 3 different averages (7 ; 9 ; 8) in the Rezultatai1.txt file. But I only get -2143899376 result.

The problem isn't the huge number, I need the program to give every row's average number separately in the output file, so that in the output file its written (7 ; 9 ; 8)

Upvotes: 1

Views: 178

Answers (3)

Shreevardhan
Shreevardhan

Reputation: 12641

I'd suggest this

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    freopen("Duomenys1.txt", "r", stdin);    // Reopen stream with different file
    freopen("Rezultatai1.txt", "w", stdout);
    int n, a, b, c;
    cin >> n;
    while (n--) {
        cin >> a >> b >> c;
        cout << (a + b + c) / 3 << endl;
    }
    return 0;
}

Input

3
5 7 4
9 9 8
8 7 8

Output

5
8
7

See DEMO.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409364

Two problems: First of all you don't do any rounding, instead since you use integer arithmetic the result is truncated. There are a couple of ways to do rounding, one of the simple is to use floating point arithmetic, and use e.g. std::round (or std::lround) to round to nearest integer value. Like e.g.

d = std::round((a + b + c) / 3.0);

Notice the use of the floating point literal 3.0 when dividing.

The second problem is that you don't write the averages, you sum all averages and write the sum. This can be fixed by simple write the average in the loop instead of after the loop, and use plain assignment instead of increase-and-assign.

Upvotes: 1

Walter
Walter

Reputation: 45444

You must make one output per line and you must use floating point arithmetic followed by rounding if you want rounded averages.

#include <iostream>
#include <iostream>
#include <cmath>

int main()
{
  const int numbers_per_lines = 3;
  std::ofstream output("Rezultatai1.txt");
  std::ifstream input("Duomenys1.txt");
  int number_of_lines;
  input >> number_of_lines;
  for(int i=0; i<number_of_lines; ++i) {
    double sum=0;
    for(int num=0; num<numbers_per_line; ++num) {
      double x;
      input >> x;
      sum += x;
    }
    output << i << ' ' << std::round(sum/numbers_per_line) << std::endl;
  }
}

Upvotes: 1

Related Questions