How to sum some float
Nov 13, 2020 at 10:27am UTC
In this code I want to read last n lines that contain float numbers and get an average of them, I get right float but the result of sum and average is not true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
using std::cout;
#include <fstream>
using std::ifstream;
#include <string>
using std::string;
using std::getline;
size_t count_lines(const char *filename)
{
ifstream myfile("test.txt" );
string line;
size_t count = 0;
while ( getline(myfile, line) )
{
++count;
}
return count;
}
int main()
{
const char filename[] = "test.txt" ;
size_t i, count = count_lines(filename);
ifstream myfile(filename);
string line;
for ( i = 0; i < count - 10; ++i )
{
getline(myfile, line); /* read and discard: skip line */
}
while ( getline(myfile, line) )
{
cout << line << "\n" ;
cl =stof(line); //The conversion works properly
cl +=cl; // The sum does not work properly
cl = cl /10.0 //The avarage does not work properly
cout<< "avarage:" << cl <<endl;
}
return 0;
}
Last edited on Nov 13, 2020 at 10:31am UTC
Nov 13, 2020 at 11:25am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <fstream>
#include <vector>
#include <numeric>
int main()
{
const char filename[] {"test.txt" };
const int last {10};
std::ifstream myFile(filename);
if (!myFile.is_open())
return (std::cout << "Cannot open file\n" ), 1;
std::vector<float > data;
for (float f {}; myFile >> f; data.push_back(f));
if (data.size() < last)
return (std::cout << "Insufficient numbers\n" ), 2;
std::cout << "Average: " << std::accumulate(data.crbegin(), data.crbegin() + last, 0.0) / last;
}
Topic archived. No new replies allowed.