Search code examples
c++decimalscientific-computing

Trying to extend my result to have 8 digits after a decimal


I'm trying to extend the result on my program to 8 digits after the decimal point. I went over this page (http://www.cplusplus.com/reference/ios/ios_base/precision/) but I'm not having any luck changing the result. Any suggestions? Thanks you.

#include <iostream>
#include <math.h>

using namespace std;

long double taylorSeriesToCalculateCosine(long double x, int degree);
long factorial( int input );

int main(int argc, const char * argv[])
{
    cout << "Cosine of .3: ";
    cout << taylorSeriesToCalculateCosine(.3,3) << endl;

    return 0;
}

// taylor series to calculate cosine
long double taylorSeriesToCalculateCosine(long double x,int degree){

    int i = 0;
    long double accumulation = 0;
    int cosInputArray[4] = {1,0,-1,0};

    while (i < degree) {

        int input = cosInputArray[i%4];

        accumulation += input*((pow(x, i))/factorial(i)); 
        i++;
    }

    return accumulation;
}

OUTPUT:

Cosine of .3: 0.955

Solution

  • You need std::setprecision from the <iomanip> header:

    cout << setprecision( 8 ) << taylorSeriesToCalculateCosine(.3,3) << endl;
    

    If you want the result to always have a certain width, use

    cout << setfill('0') << left << setw(10) << setprecision(8)
         << taylorSeriesToCalculateCosine(.3,3) << endl;