c++
输入x,求sinx。要求误差 e < 1.0 ∗ 1 0 − 9 e<1.0*10^{-9} e<1.0∗10−9
计算式: s i n x = x − x 3 3 ! + x 5 5 ! − x 7 7 ! + . . . . . . sinx=x-\frac{x^{3}}{3!}+\frac{x^{5}}{5!}-\frac{x^{7}}{7!}+...... sinx=x−3!x3+5!x5−7!x7+......
(注:这道题对于我这个新手来说,其实还是蛮有意思的,错了很多次,终于得出了自己认为还算正确的答案,借此机会分享一下。如果有错误,也希望可以有大佬指正。)
do…while循环
#include<iostream>
#include<cmath>
using namespace std;
int main(){
double x,t,t0;
int sign,n;//sign为改变符号的变量
sign = 1;n = 1;
cout<<"x=";
cin>>x;
t0 = 0;//t0初始值
t=x;//n=1时
do{
t0 += t;
sign = -sign;
n +=2;
t = sign * fabs(t) * x * x / (n * (n - 1));
} while(fabs(t0-t)>=1e-9);
cout<<"sinx="<<t0<<endl;
system("pause");
}
以及for循环(感觉自己弄的这个几乎没有什么改动)
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double x, t, t0;
int n ,sign;
n = 1; sign = 1;
cout<<"x=";
cin >> x;
t = x;//n=1时
t0 = 0;//t0初始值
for (; fabs(t0 - t) >= 1e-9;)
{
t0 += t;
sign = -sign;
n += 2;
t = sign * fabs(t) * x * x / (n * (n - 1));
}
cout << "sinx=" << t0 << endl;
system("pause");
}