问题描述
#include<iostream>
#include<conio.h>
using namespace std;
#define pi 3.1415
int main(){
system("cls");
float x;
int n;
cout<<"Enter the value of x(degree) : ";
cin>>x;
cout<<"Enter the value of n : ";
cin>>n;
cout<<"The value of Cos("<<x<<") is : ";
x = x*pi/180;
float temp = 1,cos=1;
for(int i=0; i<=n; i++){
temp *= (-1)*(x*x)/((i+2)*(i+1));
cos += temp;
}
cout<<cos;
getch();
system("cls");
}
我也尝试了更大的 pi 值,但在第二个小数点处得到的值仍然非常不准确。
解决方法
for(int i=0; i<=n; i++){
temp *= (-1)*(x*x)/((i+2)*(i+1));
cos += temp;
}
当 i==0
时,您将 temp
乘以 (-1)*(x*x)/(2*1)
,这很好。当 i==1
乘以不太好的 (-1)*(x*x)/(3*2)
时,分母中的 4*3
应该以 x^4/4!
结尾。
每次循环时,您都需要将 i
增加 2,而不是 1。因此将 i++
更改为 i += 2
。