PHP类未通过输入测试(家庭作业帮助)
我创建了一个类,它获取作物列表并返回任何特定作物的比率。它是这样使用的:PHP类未通过输入测试(家庭作业帮助),php,Php,我创建了一个类,它获取作物列表并返回任何特定作物的比率。它是这样使用的: $cropRatio = new CropRatio; $cropRatio->add('Wheat', 4); $cropRatio->add('Wheat', 5); $cropRatio->add('rice', 1); echo "Wheat: " . $cropRatio->proportion('Wheat'); //Output: Wheat is .9 根据小麦
$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('rice', 1);
echo "Wheat: " . $cropRatio->proportion('Wheat'); //Output: Wheat is .9
根据小麦和大米的这些值,答案是正确的。但是,我编写的类没有通过,因为系统说它在使用多种类型的输入进行测试时抛出异常
作业软件会给出以下错误:
class CropRatio
{
private $totalWeight;
private $crops = [];
public function add(string $name, int $cropWeight) : void
{
$name = ucfirst(trim($name));
if(is_string($name) && is_int($cropWeight))
{
if(!array_key_exists($name, $this->crops)) {
$this->crops[$name] = $cropWeight;
}
else
{
$this->crops[$name] += $cropWeight;
}
$this->totalWeight += $cropWeight;
}
}
public function proportion(string $name) : float
{
if($this->totalWeight > 0)
{
return $this->crops[$name] / $this->totalWeight;
}
else
{
return 0;
}
}
}
$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('rice', 1);
echo "Wheat: " . $cropRatio->proportion('Wheat'); //Output: Wheat is .9
有人能指出这个类在输入测试中失败的原因吗?您需要考虑参数列表。什么样的论点是有效的,有多少论点需要有正确的比例。事实上,线索就在错误中。如果我测试它,给它一些
污点
作为参数,它还会有效吗?@Kevin抱歉,我可能没有完全遵循这个原则。时间不早了,我已经在这个问题上纠缠了好几个小时了。给它一些污垢,你的意思是$cropRatio->add('dirt')?我用$cropRation->add添加了数千种不同的作物,没有错误。对于零作物,我也没有看到任何错误。然而,测试软件仍然告诉我:1)几个作物:错误2)只有一个作物:错误3)零作物:错误