Scan an angle xdeg in degrees, calculate the corresponding value x in radians, a
ID: 3630890 • Letter: S
Question
Scan an angle xdeg in degrees, calculate the correspondingvalue x in radians, and evaluate y=cos(x) by using the
math.h library of functions. Define PI to be 3.141592654.
Your objective in this homework is to compare the so calculated
value of y with the approximate value Y obtained by
using either 2, 3, 4 or 5 leading terms of the Taylor series:
cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - ....
Use the for loop for each k to evaluate k!=k*(k-1)*(k-2)* ... *3*2*1.
Use a switch statement switch(int), with cases 2-5, selected
by using the scanf() function.
Take care about the unrecognized entry for switch().
Evaluate the corresponding Y, print the result in one line,
and the relative percent error RE=100*(Y-y)/y in another line.
Your output should be like this:
Enter xdeg in degrees: 60
True value of cos(60.00) = 0.500000
Enter the integer 2-5:
3
3 term(s) approximation
Approximate cos(60.00) = 0.501796
Relative Error = 0.359240 percent
[me9z@iacs5]:homework:213% a.out
Enter xdeg in degrees: 60
True value of cos(60.00) = 0.500000
Enter the integer 2-5:
6
unrecognized operator
*/
Explanation / Answer
#include <stdio.h>
#include <math.h>
#include <conio.h>
int fact(int);
double coss(int,double);
int main()
{double xdeg,rad,truecos,mycos,PI=3.141592654,RE;
int i;
printf("Enter xdeg in degrees: ");
scanf("%lf",&xdeg);
rad=xdeg*PI/180;
truecos=cos(rad);
printf("True value of cos(%.2f) = %f ",xdeg,truecos);
printf("Enter the integer 2-5: ");
scanf("%d",&i);
switch(i)
{case 2:
case 3:
case 4:
case 5: mycos=coss(i,rad);
printf("Approximate cos(%.2f) = %f ",xdeg,mycos);
RE=100*(mycos-truecos)/truecos;
printf("Relative Error = %f percent ",RE);
break;
default: printf("unrecognized operator ");
}
getch();
return 0;
}
double coss(int n,double x)
{int flip,i;
double term,next;
term=1;
flip=-1;
for (i=2;i<=(n-1)*2;i+=2)
{next=(pow(x,i)/fact(i))*flip;
printf("%f ",next);
flip*=-1;
term+=next;
}
return term;
}
int fact(int n)
{int i,m;
m=1;
for(i=1;i<=n;i++)
m*=i;
printf("%d ",m);
return m;
}