请问这个算式用java怎么编写?

2025-02-25 17:07:35
推荐回答(1个)
回答1:

package com;

import java.util.Scanner;

public class Exam
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("input the n: ");
int n = scanner.nextInt();
scanner.close();
double sn = 0;
String result = "";
for(int i = 1; i <= n; i++)
{
int fenzi = (int) Math.pow(-1, i - 1);
String tag = fenzi > 0 ? i != 1 ? "+" : "" : "-";
long fenmu = (long) Math.pow(2, i - 1);
result += tag + "1/" + fenmu;
sn += fenzi * 1.0 / fenmu;
}
System.out.format("%f%nSn=%s", sn, result);
}
}