这个问题之前有人问过的,,而且我也答过0.0
你可以参见:http://zhidao.baidu.com/question/1238984228162181339.html?oldq=1
或者我把代码也贴在这边,运行的结果,,你可以点击上面的问题查看,,我就不赘述了,看不懂的可以问。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
System.out.println("Please input integer n:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
double sum = 0;
for (int i = 0; i < n; i++) {
sum += get(i + 1) / get(i);
}
File file = new File("java_15.txt");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write("前" + n + "个数的和为:" + sum);
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static double get(int i) {
if (i == 0)
return 1;
if (i == 1)
return 2;
return get(i - 1) + get(i - 2);
}
}
输入格式要按照你上面的来,分数由“,”分开,分子分母由“/”分开。
代码如下:
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入:");
String str = br.readLine();
String[] strs = str.split(",");
double a = 1; // 分母
double b = 1; // 分子
for (String s : strs) {
String[] num = s.split("/");
a *= Integer.parseInt(num[0]);
b *= Integer.parseInt(num[1]);
}
System.out.println(a/b);
} catch (Exception e) {
}
}