1 添加一个类 Fraction 表示分数
package my;
public class Fraction
{
public int num; // 分子
public int den; // 分母
// 显示分数的值: 如 4/5 形式
public String value()
{
return num + "/" + den;
}
// 分数的乘法 ( 小学算术 )
public Fraction mul ( Fraction other) // 参数other指向另一个Fraction对象 (参照网盘里第8章的补充教程)
{
// 分子分母交叉相乘相加, 分母相乘
Fraction result = new Fraction();
result.num = this.num * other.num;
result.den = this.den * other.den;
return result;
}
}
2 使用这个类
package my;
public class HelloWorld
{
public static void main(String[] args)
{
Fraction a = new Fraction(); // a: 1/3
a.num = 1;
a.den = 3;
Fraction b = new Fraction(); // b: 2/5
b.num = 2;
b.den = 5;
Fraction c = a.mul( b); // a,b相乘
System.out.println("a * b = " + c.value()); // c.value() 是将结果以分数形式显示
}
}