#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)
答案 0 :(得分:1)
每行必须输出一个输出,如果想要舍入平均值,则必须使用浮点运算然后舍入。
#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;
}
}
答案 1 :(得分:1)
两个问题:首先,你不进行任何舍入,而是因为你使用整数运算,结果是截断。有几种方法可以进行舍入,其中一种方法是使用浮点算法,并使用例如std::round
(or std::lround
)舍入到最接近的整数值。比如说。
d = std::round((a + b + c) / 3.0);
注意分割时使用浮点文字3.0
。
第二个问题是你没有写平均数,你总结所有平均数并写出总和。这可以通过简单地在循环中而不是在循环之后写入平均值来修复,并使用普通赋值而不是增加和赋值。
答案 2 :(得分:0)
我建议这个
var file_url = 'http://aws_s3_or_any_other_url';
var filePath = 'local/path/to/your/file';
var downloadFile = new FileTransfer();
var encoded_url = encodeURI(url);
downloadFile.download(
uri,
filePath,
function(success) {
console.log("download complete: " + success.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Token XXXXXXX*"
}
}
);
<强>输入强>
#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
参见 DEMO 。