c++输入/输出

C++ Input/output

本文关键字:输出 输入 c++      更新时间:2023-10-16
#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;
}

程序应该读取3(3为n)行数字(5 7 4;9 9 8;8 7 8),行分别求和并给出3个不同的平均值(7;9;8)在Rezultatai1.txt文件中。但是我只得到-2143899376的结果。

问题不是巨大的数字,我需要程序在输出文件中分别给出每一行的平均值,以便在输出文件中写入(7;9;8)

你必须每行输出一个,如果你想要四舍五入的平均值,你必须使用浮点运算。

#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;
  }
}

有两个问题:首先,您没有做任何舍入,相反,由于您使用整数算术,结果是截断的。有几种方法可以进行舍入,其中一种简单的方法是使用浮点算术,并使用例如std::round(或std::lround)来舍入到最接近的整数值。像如。

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

注意除法时使用的浮点文字3.0

第二个问题是你不写平均值,你把所有平均值加起来,然后写总和。这可以通过简单地在循环中而不是在循环后写入平均值,并使用普通赋值而不是递增和赋值来解决。

我建议这样做

#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;
}
输入

3
5 7 4
9 9 8
8 7 8

5
8
7
<<p>看到演示/kbd>。