1 条题解

  • 0
    @ 2023-6-11 12:17:58

    C :

    #include<stdio.h>
    
    void main(){
        double s=0;
        int i,n,f=1;
        scanf("%d",&n);
    
        for(i=1;i<=n;i++){
            s=s+1.0*f/i;
            f=f*-1;
        }  
        printf("%.4f",s);
    }
    

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        float s = 0;
    	int i,f = 1,n;
    	cin>>n;
    	for(i = 1;i <= n;i++){
    		s = s + 1.0 * f / i;
    		f = f * -1;
    	} 
        cout<<fixed<<setprecision(4)<<s<<endl;
    } 
    

    Java :

    import java.util.*;
    public class Main{
    	public static void main(String args[]){
    		Scanner in = new Scanner(System.in);
    		int n = in.nextInt();
    		double a = 1.0;
    		double sum = 0;
    		for(int i = 1;i<=n;i++){
    			if(i%2==0){
    				 sum =sum-(a/i);
    			}else{
    				sum =sum+(a/i);
    			}
    		}
    		System.out.println(String.format("%.4f",sum));
    	}
    }
    

    Python :

    n=int(input())
    i=1
    j=2
    a=0
    b=0
    while i<=n:
        a+=1/i
        i+=1
    while j<=n:
        b+=1/j
        j+=2
    print('{:.4f}'.format(a-2*b))
    
    • 1

    【入门】计算分数加减表达式的值

    信息

    ID
    2441
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者