For some home work I'm doing the following:
int main() {
ofstream file("log.txt");
file << setw(5) << "i"
<< setw(15) << "h"
<< setw(15) << "n"
<< setw(15) << "sum"
<< setw(15) << "diff"
<< endl;
auto write2file = [&file](int i, double h, double n, double sum, double diff) {
file << setw(5) << i
<< setw(15) << h
<< setw(15) << n
<< setw(15) << sum
<< setw(15) << diff
<< endl;
};
double a = 0;
double b = 2;
int n = 1;
double h = (b-a)/n;
double sum = sum_analytic;
double diff = 1;
while (diff > pow(10, -4)) {
h = (b-a)/++n;
sum = ntgrt(a, b, n, h);
diff = abs(sum - sum_analytic);
static int i = 0;
write2file(++i, h, n, sum, diff);
}
}
Considering the C++17 if init
feature (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0305r1.html) I'm kind of seing the same pattern here when I declare h
, sum
and diff
outside the while
loop but they are used only inside.
Is there a better way to write it, may be taking advantage of C++17 features?