(https://i.stack.imgur.com/3LgGA.png) I have been trying to make a code in c++ for the Mclaurin ’s Series expansion of sin(x), as a review for my Intro to Programming class and my results are always not equivalent to the sample runs. I have been trying to trouble shoot this for hours to no avail. Please help.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double factorial(int num);
double sum(double number, int n);
int main() {
double number, sin;
int n;
cout<<"Enter the value of x: ";
cin>>number;
cout<<"Enter the number of terms: ";
cin>>n;
sin=sum(number,n);
cout<<"sin("<<number<<") = "<<fixed<<showpoint<<setprecision(6)<<sin<<endl;
return 0;
}
double factorial(int num){
double sum=1;
for(int x=num; x>=1;x--){
sum*=x;
}
return sum;
}
double sum(double number, int n){
int count=3;
double term,term1, sum=0, sum2=0, totalSum;
for(int i=1;i<n-1;i+=2 ){
term1=(pow(number, count))/ factorial(count);
sum+=term1;
count+=4;
}
for(int j=0;j<n-2;j+=2){
term=pow(number, count)/ factorial(count);
sum2+=term;
count+=4;
}
totalSum=number+sum+sum2;
return totalSum;
}
Aucun commentaire:
Enregistrer un commentaire