题目背景
已 知 s i n x = ∑ n = 1 ∞ ( − 1 ) n − 1 x 2 n − 1 ( 2 n − 1 ) ! n = 1 ∑ ∞ ( − 1 ) n − 1 ( 2 n − 1 ) ! x 2 n − 1 已知 sinx=\displaystyle \sum^{\infty}_{n=1}(-1)^{n-1}\frac{x^{2n-1}}{(2n-1)!} n=1 ∑ ∞ (−1) n−1 (2n−1)! x 2n−1 已知sinx=n=1∑∞(−1)n−1(2n−1)!x2n−1n=1∑∞(−1)n−1(2n−1)!x2n−1
题目描述
现在已知一个xx,需要聪明的你来求sinx的近似值(数值精确10^{-7}10
−7
)(不用四舍五入)
输入格式
输入共一行,一个整数xx
输出格式
sinx的近似值
输入输出样例
无
说明/提示
0≤x≤7
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
int main(){
double x,k=1;
cin>>x;
double sum=0,temp1=1,temp2=x,temp3=1;
for(int i=1;temp1>=1e-7;i+=2){
temp1 = temp2 / temp3;
sum = sum + k * temp1;
temp2 = temp2 * x * x;
temp3 = temp3 * (i+1) * (i+2);
k = -k;
}
cout<<fixed<<setprecision(9);
cout<<sin(x)<<"\n";
cout<<fixed<<setprecision(7);
cout<<sum<<"\n";
return 0;
}
上面是我个人写的,但是洛谷拿不到满分不知道为甚么?唉,下面分享一个满分答案。
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int main()
{
int x;
cin >>x;
double temp=x,s=0;
for(int i=1;fabs(temp)>=1e-7;i+=2)
{
s+=temp;
temp=temp*(-x*x)/((i+1)*(i+2));
}
cout<<fixed<<setprecision(7);
cout << s;
return 0;
}
Java题解:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
double temp = x,s = 0;
for(int i=0;Math.abs(temp) >= 1e-7;i+=2){
s += temp;
temp = temp*(-x * x) / ((i+1) * (i+2));
}
System.out.printf("%.7f",s);
}
}