1、N个分数求和
博客链接 https://blog.csdn.net/weixin_73142957/article/details/128798429
public class Demo3_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int sumA = 0;//分子和
int sumB = 0;//分母和
for (int i = 0; i < n; i++) {
String[] split = scanner.next().split("/");
int a = Integer.parseInt(split[0]);//分子
int b = Integer.parseInt(split[1]);//分母
if (sumA == 0) {//只有一个算式时
sumA = a;
sumB = b;
} else {//通分
sumA = a * sumB + b * sumA;
sumB = sumB * b;
}
int max = resGcd(sumA, sumB);
//分子和分母化为最简
sumA /= max;
sumB /= max;
}
if (sumA != 0 && (sumA / sumB == 0)) {//只有分数
System.out.println(sumA + "/" + sumB);
} else if (sumA % sumB == 0) {//只有整数部分
System.out.println(sumA / sumB);
} else {//包含整数和分数
System.out.println(sumA / sumB + " " + (sumA % sumB) + "/" + sumB);
}
}
//计算最大公约数
private static int resGcd(int a, int b) {
if (b == 0) return a;
return resGcd(b, a % b);
}
}
标签:练习题,scanner,int,System,split,sumB,sumA From: https://www.cnblogs.com/huxiaoan1/p/17519156.html时间:2023-07-01