【问题标题】:C++ Input/outputC++ 输入/输出
【发布时间】:2015-10-07 23:22:09
【问题描述】:
#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),行分别汇总并在 Rezultatai1 中给出 3 个不同的平均值 (7 ; 9 ; 8) .txt 文件。但我只得到 -2143899376 结果。

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

【问题讨论】:

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

标签: c++ input output


【解决方案1】:

我建议这个

#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

DEMO

【讨论】:

    【解决方案2】:

    两个问题:首先,您不进行任何舍入,而是因为您使用整数运算,结果是截断。有几种方法可以进行舍入,其中一种简单的方法是使用 浮点 算术,并使用例如std::round (or std::lround) 舍入到最接近的整数值。比如说

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

    注意除法时使用浮点字面量3.0

    第二个问题是您不写平均值,而是将所有平均值相加并写出总和。这可以通过简单地在循环中而不是在循环之后写入平均值来解决,并使用普通分配而不是增加和分配。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-28
        相关资源
        最近更新 更多