CPPForSchool.com: Flow of Control Set 3: Assignment 3
3.
Write a program to compute the cosine of x. The user should supply x
and a positive integer n. We compute the cosine of x using the series
and the computation should use all terms in the series up through the
term involving xn
cos x = 1 - x2/2! + x4/4! - x6/6! ...
It is quite frustrating to run into the unknown and unable to decipher my lack of comprehension to the subject at hand. Although, I understand conceptually what cos x is, it does not translate to C++. Although, things may be different if I am able to use the math library in C++, this assignment is supposed to be answered utilizing loops. Like the prior assignment, I will have to omit any code and simply post the sample source code provided by CPPForSchool.
cos x = 1 - x2/2! + x4/4! - x6/6! ...
It is quite frustrating to run into the unknown and unable to decipher my lack of comprehension to the subject at hand. Although, I understand conceptually what cos x is, it does not translate to C++. Although, things may be different if I am able to use the math library in C++, this assignment is supposed to be answered utilizing loops. Like the prior assignment, I will have to omit any code and simply post the sample source code provided by CPPForSchool.
#include<iostream>
using namespace std;
int main()
{
int i,j,n,fact,sign=-1;
float x, p,sum=0;
cout<<"Enter the value of x : ";
cin>>x;
cout<<"Enter the value of n : ";
cin>>n;
for(i=2;i<=n;i+=2)
{
p=1
fact=1;
for(j=1;j<=i;j++)
{
p=p*x;
fact=fact*j;
}
sum+=sign*p/fact;
sign=-1*sign;
}
cout<<"cos "<<x<<"="<<1+sum;
return 0;
}
Comments
Post a Comment