import java.util.Scanner;
class FenShu {
long fenzi;
long fenmu;
@Override
public String toString() {
return this.fenzi + "/" + this.fenmu;
}
public FenShu(long fenzi, long fenmu) {
this.fenzi = fenzi;
this.fenmu = fenmu;
}
public long gcd(){
long min_value = Math.abs(this.fenzi) < Math.abs(this.fenmu)
? Math.abs(this.fenzi) : Math.abs(this.fenmu);
long gcd = 1;
for(long i = min_value; i > 0; i--){
if(this.fenzi % i == 0 && this.fenmu % i ==0){
gcd = i;
break;
}
}
return gcd;
}
public void simple(){
long gcd = this.gcd();
this.fenzi /= gcd;
this.fenmu /= gcd;
}
public FenShu add(FenShu other){
long newFenmu = this.fenmu * other.fenmu;
long newFenzi = this.fenzi*other.fenmu + this.fenmu*other.fenzi;
FenShu result = new FenShu(newFenzi,newFenmu);
result.simple();
return result;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
String line = scanner.nextLine();
String[] arr = line.split(" ");
FenShu result = new FenShu(0,1);
for(int i = 0; i < arr.length;i++){
String fenshuStr = arr[i];
String[] fenshuArr = fenshuStr.split("/");
FenShu fenShu = new FenShu(Long.parseLong(fenshuArr[0])
,Long.parseLong(fenshuArr[1]));
result = result.add(fenShu);
result.simple();
}
//-3/2 -> -1 -1/2
// System.out.println(result);
String prefix = "";
if(result.fenzi*1.0/result.fenmu<0){
prefix = "-";
}
long final_fenzi = Math.abs(result.fenzi);
long final_fenmu = Math.abs(result.fenmu);
//0/2
if(final_fenzi%final_fenmu==0){
System.out.println(prefix+final_fenzi/final_fenmu);
}
else if(final_fenzi < final_fenmu){
System.out.println(prefix+final_fenzi+"/"+final_fenmu);
}
else{
System.out.print(prefix+final_fenzi/final_fenmu);
System.out.print(" ");
System.out.print(prefix+final_fenzi%final_fenmu+"/"+final_fenmu);
}
}
}
L1-009 N个数求和(Java分数类)
于 2024-08-19 12:55:25 首次发布