我必须用java创建一个rational类,我需要添加gcd和一种测试它的方法 公共类主 { 公共静态void main(字符串[]args) { 有理数a=新有理数(1,2); 有理b=新有理(1,4); System.out.println(a+“+”+b+“=”+a.add(b)); 系统输出println(a+“-”+b+“=”+a.sub(b)); 系统输出println(a+“*”+b+“=”+a.mul(b)); 系统输出println(a+“/”+b+“=”+a.div(b)); } } 类理性 { 私有整数分子、分母; 公共有理数(整数,整数) { 如果(denom==0) denom=1; 如果(denom
我已经完成了所有这些工作: 建造师 添加 附属的 骡子 div 托斯特林我必须用java创建一个rational类,我需要添加gcd和一种测试它的方法 公共类主 { 公共静态void main(字符串[]args) { 有理数a=新有理数(1,2); 有理b=新有理(1,4); System.out.println(a+“+”+b+“=”+a.add(b)); 系统输出println(a+“-”+b+“=”+a.sub(b)); 系统输出println(a+“*”+b+“=”+a.mul(b)); 系统输出println(a+“/”+b+“=”+a.div(b)); } } 类理性 { 私有整数分子、分母; 公共有理数(整数,整数) { 如果(denom==0) denom=1; 如果(denom,java,Java,我已经完成了所有这些工作: 建造师 添加 附属的 骡子 div 托斯特林 我只需要gcd和一个测试方法,我不确定如何将gcd实现到我的代码中,如果有人能帮忙的话,那就太好了,感谢高级版。这是它的伪代码,取自维基百科,以及递归版本。您应该能够在Java中实现它们中的任何一个。我会将此作为评论发布,因为这不是一个真正的答案,但格式会很糟糕 public class Main { public static void main(String[] args) { Rati
我只需要gcd和一个测试方法,我不确定如何将gcd实现到我的代码中,如果有人能帮忙的话,那就太好了,感谢高级版。这是它的伪代码,取自维基百科,以及递归版本。您应该能够在Java中实现它们中的任何一个。我会将此作为评论发布,因为这不是一个真正的答案,但格式会很糟糕
public class Main
{
public static void main(String[] args)
{
Rational a = new Rational(1,2);
Rational b = new Rational(1,4);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class Rational
{
private int numerator, denominator;
public Rational (int numer, int denom)
{
if (denom == 0)
denom = 1;
if (denom < 0)
{
numer = numer * -1;
denom = denom * -1;
}
numerator = numer;
denominator = denom;
}
public Rational add (Rational b)
{
int commonDenominator = denominator * b.getDenominator();
int numerator1 = numerator * b.getDenominator();
int numerator2 = b.getNumerator() * denominator;
int sum = numerator1 + numerator2;
return new Rational (sum, commonDenominator);
}
public Rational sub(Rational b) {
int commonDenominator = denominator * b.getDenominator();
int numerator1 = numerator * b.getDenominator();
int numerator2 = b.getNumerator() * denominator;
int difference = numerator1 - numerator2;
return new Rational (difference, commonDenominator);
}
public Rational mul(Rational b) {
int numer = numerator * b.getNumerator();
int denom = denominator * b.getDenominator();
return new Rational (numer, denom);
}
public Rational div(Rational b) {
return mul (b.reciprocal());
}
public int getNumerator ()
{
return numerator;
}
public int getDenominator ()
{
return denominator;
}
public Rational reciprocal ()
{
return new Rational (denominator, numerator);
}
public String toString ()
{
String result;
if (numerator == 0)
result = "0";
else
if (denominator == 1)
result = numerator + "";
else
result = numerator + "/" + denominator;
return result;
}
}
我应该用欧几里德算法为GCD编写代码。不客气,可能是你的副本。
function gcd(a, b)
while b ≠ 0
t := b;
b := a mod b;
a := t;
return a;
function gcd_r(a,b) {
if (b = 0) {
return a;
}
return gcd_r( b, a mod b );
}