Weird problem while trying to write to file

I want to write output to a file, but I have encountered a weird problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    double function_hw(double x);
    double difference_quotient(double x, double h);
    double x = 1.0, h = 0.000001;
    double analytical = (sin(x)*2*x - pow(x,2)*cos(x))/pow(sin(x),2);
    ofstream myfile ("Numerical_Derivative.txt");
        
    cout.unsetf(ios::floatfield);
    cout.precision(12);
    
    for(; h>= -0.00001; h -= 0.00000001){
        cout << difference_quotient(x, h)- analytical << endl;
        myfile << difference_quotient(x, h)- analytical << endl;}

    
    return 0;
}


double function_hw(double x) { return pow(x,2)/sin(x);}

double difference_quotient(double x, double h) {return (function_hw(x+h) - function_hw(x))/h;}



Now the problem has to do with the combination of the variable "analytical" and the opening of the file. If I just run the program writing output on the standard output, and not open the file, everything is fine and if I comment out the variable analytical and write something random onto myfile, it also works. But when I include "analytical" and open the file, the program fails.

Does anybody have an idea why this might be the case and what is happening here? I don't know too much about reading/writing on files, I just read the tutorial on this site.
Last edited on
what do you mean by the program fails ? what do you expect to be printed on the file and in std output, do they differ ? if that is the case, try adding:
myfile.unsetf( ios::floatfield ); and myfile.precision( 12 ); to myfile stream also
Last edited on
Topic archived. No new replies allowed.