c++输入/输出
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;
}
程序应该读取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>。 相关文章:
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++多个输入和输出
- 制定带有输入和输出C++的时间表
- 字符的输入/输出操作
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- C++ 中的矢量重复输出输入
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 在输出输入文本时对齐输入的文本
- 将多个文件输出/输入到桌面
- 输出输入c++的最短方式
- 将Crypto++中自动种子PNRG的输出输入一个字符串
- 输出输入的拼接版本