我想检查一个输入的三角形是等腰,等等。第一个if语句是否有效,但是一旦我引入了第二个,它就说出了意想不到的t_else,这里是代码......
public function typeOfTriangle()
{
if ($this->sideOneLength == $this->sideTwoLength && $this->sideTwoLength == $this->baseLength) {
echo "<h1>Equilateral Triangle</h1>";
else if ($this->sideOneLength == $this->sideTwoLength OR $this->sideOneLength == $this->baseLength OR $this->sideTwoLength == $this->baseLength) {
echo "<h1>Isosceles Triangle</h1>";
}
}
任何想法?
答案 0 :(得分:0)
您遇到语法错误:
public function typeOfTriangle()
{
if ($this->sideOneLength == $this->sideTwoLength && $this->sideTwoLength == $this->baseLength) {
echo "<h1>Equilateral Triangle</h1>";
}else if ($this->sideOneLength == $this->sideTwoLength OR $this->sideOneLength == $this->baseLength OR $this->sideTwoLength == $this->baseLength) {
echo "<h1>Isosceles Triangle</h1>";
}
}
答案 1 :(得分:0)
需要大括号}
if ($this->sideOneLength == $this->sideTwoLength && $this->sideTwoLength == $this->baseLength) {
echo "<h1>Equilateral Triangle</h1>";
}
else if ($this->sideOneLength == $this->sideTwoLength OR $this->sideOneLength == $this->baseLength OR $this->sideTwoLength == $this->baseLength) {
echo "<h1>Isosceles Triangle</h1>";
}
答案 2 :(得分:0)
我建议采用略有不同,更具可读性的方法:
public function getSides()
{
return array($this->sideOneLength, $this->sideTwoLength, $this->sideThreeLength);
}
public function typeOfTriangle()
{
$uniqueSides = count(array_unique($this->getSides()));
if ($uniqueSides == 1) {
return "Equilateral";
} elseif ($uniqueSides == 2) {
return "Isosceles";
} else {
return "Normal triangle";
}
}
答案 3 :(得分:0)
也许这更好? (基于Vlad Preda的例子:
public function getSides()
{
return array($this->sideOneLength, $this->sideTwoLength, $this->sideThreeLength);
}
public function typeOfTriangle()
{
$uniqueSides = count(array_unique($this->getSides()));
switch ($uniqueSides) {
case 1:
return "Equilateral";
break;
case 2:
return "Isosceles";
break;
default:
return "Normal triangle";
break;
}
}