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
有了小麦和大米的这些值,答案就正确了。但是,我编写的类没有通过,因为系统说它在使用多种类型的输入进行测试时抛出异常。
作业软件给出这些错误:
- 示例案例:错误 - 分析您的代码将如何对不同的输入做出反应
- 几种作物:错误 - 分析您的代码将如何对不同的输入做出反应
- 只有一种作物:错误 - 分析您的代码将如何对不同的输入做出反应
- 零作物:错误 - 分析您的代码对不同输入的反应
我必须缺少几种类型的输入验证?
这是课程:
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
谁能指出为什么这个类没有通过输入测试?
解决方案
主要问题是总重量,所以如果总重量不正确,那么您就无法计算比率。到目前为止,要解决此问题,您必须检查以前的作物重量并相应地修改当前作物重量和总重量
class CropRatio
{
public $totalWeight;
public $crops = [];
public function add(string $name, int $cropWeight) : void
{
if(!array_key_exists($name, $this->crops)) {
$this->crops[$name] = $cropWeight;
}
else
{
$pre_weight = $this->crops[$name]; // this one was missing - very important
$this->crops[$name] = $pre_weight + $cropWeight;
}
$this->totalWeight+=$cropWeight;
}
public function proportion(string $name) : Float
{
return $this->crops[$name] / $this->totalWeight;
}
}
$cropRatio = new CropRatio;
$cropRatio->add('Wheat', 4);
$cropRatio->add('Wheat', 5);
$cropRatio->add('Rice', 1);
echo "Wheat: " . $cropRatio->proportion('Wheat');
推荐阅读
- android - android.graphics 从一个 View 画一条线指向另一个 View
- apache-spark - 如何在 Apache Spark Java 或 Scala 中实现这一点?
- java - 表单数据未保存在会话中
- powershell - 从另一个 PowerShell 控制台获取数据
- sql - 当星期从星期三开始时,SQLlite 将日期列格式化为星期数
- azure-automation - 没有输出流的 Azure 自动化测试窗格
- python - pytest 的设置时间慢,如何减少?
- javascript - 如何从另一个表制作我的 php 表
- php - PHP MySQL选择最近n分钟内日期时间值的行
- ios - 在 xcode 9 中使用 auk 创建圆形图像