【题解】【循环】幂级数求和

题目背景

已 知 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)n1(2n1)!x2n1n=1(1)n1(2n1)!x2n1


题目描述

现在已知一个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);

    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值