C++ C++;输入/输出 #包括 #包括 使用名称空间std; int main() { int a,b,c,i,n; int d=0; ifstreammyfile; myfile.open(“Duomenys1.txt”); myfile>>n; 对于(int i=0;i>a>>b>>c; d+=(a+b+c)/3; } 流式肌瘤锉; myotherfile.open(“Rezultatai1.txt”); myotherfile

C++ C++;输入/输出 #包括 #包括 使用名称空间std; int main() { int a,b,c,i,n; int d=0; ifstreammyfile; myfile.open(“Duomenys1.txt”); myfile>>n; 对于(int i=0;i>a>>b>>c; d+=(a+b+c)/3; } 流式肌瘤锉; myotherfile.open(“Rezultatai1.txt”); myotherfile,c++,input,output,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 (

如果您想要四舍五入的平均值,您必须每行输出一个输出,并且必须使用浮点算术,然后使用四舍五入

#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;
}
#包括
#包括
#包括
int main()
{
每行的常数整数=3;
流输出的std::(“Rezultatai1.txt”);
std::ifstream输入(“Duomenys1.txt”);
整数行数;
输入>>行数;
对于(int i=0;i x;
总和+=x;
}

输出两个问题:首先,你不做任何舍入,而是因为你使用整型算法,结果被截断。有两种方法可以进行舍入,其中一种简单的方法是使用浮点算法,并使用例如舍入到最接近的整数值。例如

#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;
  }
}
请注意在除法时使用浮点文本
3.0

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

我建议这样做

d = std::round((a + b + c) / 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

请参阅。

您显示的程序是您运行的实际程序吗?您为输入文件显示的数据是实际数据吗?然后您应该在输出文件中得到
20
。对我来说效果很好(结果是
5+8+7=20
)。您的输入文件看起来如何?顺便说一句,整数算术给出
(9+9+8)/3=8
不是
9
@Walter我只是用OP提供的数字作为平均值,尽管它们是错误的。@JoachimPileborg从不相信OP@ParanoidParrot程序中没有舍入,只使用整数算术,因此结果会被截断。
5
8
7