public function add($temp) {
$newNum = $this->num + $temp->num;
if($this->denum == $temp->denum) {
// add two fractions having same denominator
$answer = $newNum . "/" . $this->denum;
} else {
// how to add two fractions having different denominator?
}
return $answer;
}
换句话说,如何处理具有不同分母的两个分数的情况,如:
1/3 + 1/6 = 3/6
或
1/3 + 1/5 = 8/15
答案 0 :(得分:3)
function gcd($num1, $num2) {
/* finds the greatest common factor between two numbers */
if ($num1 < $num2) {
$t = $num1;
$num1 = $num2;
$num2 = $t;
}
while ($t = ($num1 % $num2) != 0) {
$num1 = $num2;
$num2 = $t;
}
return $num2;
}
public function add($temp) {
$newNum = $this->num * $temp->denum + $temp->num * $this->denum;
$newDenum = $temp->denum * $this->denum;
$gcd = gcd($newNum, $newDenum);
$newNum /= $gcd;
$newDenum /= $gcd;
return $newNum . '/' . $newDenum;
}
答案 1 :(得分:0)
假设您要添加1/3到1/6,只需执行
$result = 1/3 + 1/6;
答案 2 :(得分:0)
这不会减少你的分数,但除此之外它应该做你想要的:
public function add($temp) {
if($this->denum == $temp->denum) {
$newNum = $this->num + $temp->num;
$answer = $newNum . "/" . $this->denum;
} else {
$newNum = $this->num * $temp->denum + $temp->num * $this->denum;
$answer = $newNum . "/" . $this->denum*$temp->denum;
}
return $answer;
}