该题目实现了分数的表示,分数的加法和乘法。该题目的输入不需要考虑输入分母为“0”。注意,例如当输入是分子是4,分母是8的时候,分数应该是1/2,而不是4/8.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fraction a = new Fraction(in.nextInt(), in.nextInt());
Fraction b = new Fraction(in.nextInt(),in.nextInt());
a.print();
b.print();
a.plus(b).print();
a.multiply(b).print();
in.close();
}
}
/* 请在这里填写答案 */
class Fraction
{
int a, b;
Fraction(int x, int y)
{
this.a = x;
this.b = y;
}
Fraction plus(Fraction x)
{
Fraction r = new Fraction(0,0);
r.a =this.a * x.b + this.b * x.a;//fenzi
r.b =this.b * x.b;//fenmu
return r;
}
Fraction multiply(Fraction x)
{
this.a = this.a * x.a;
this.b = this.b * x.b;
return this;
}
void print()
{
int h ;
if(this.a > this.b )
{
h = GCD(this.a, this.b) ;
}
else
{
h = GCD(this.b, this.a);
}
this.a /= h;
this.b /= h;
System.out.print(this.a+"/"+this.b+' ');
}
public int GCD(int x,int y)
{
if(x %y == 0) return y;
return GCD(y, x % y);
}
}
6 - 18 PTA分数计算实现
这篇博客主要介绍了如何实现分数的表示,包括分数的加法和乘法运算。在处理输入时,确保不会出现分母为0的情况。同时强调,输入如4/8应简化为1/2。
681





