javascript - If 语句未通过测试用例

标签 javascript if-statement

您好,我正在处理 codefights 挑战,我花了很多时间试图解决这个问题,我的所有测试用例都通过了我给出的测试用例,我还有 4 个需要通过的隐藏测试用例,但是我正在通过除一个隐藏测试用例之外的所有测试用例。我的大脑已经完全绞尽脑汁,我已经创建了所有我能想到的自己的测试用例,并且所有这些都很好地通过了。这只是一个隐藏的情况,我尝试过类型检查,似乎一切都在检查。

n children have got m pieces of candy. They want to eat as much candy as
they can, but each child must eat exactly the same amount of candy as any > other child. Determine how many pieces of candy will be eaten by all the
children together. Individual pieces of candy cannot be split.

Example

For n = 3 and m = 10, the output should be candies(n, m) = 9.

Each child will eat 3 pieces. So the answer is 9.

Input/Output

[time limit] 4000ms (js)

[input] integer n

The number of children.

Constraints: 1 ≤ n ≤ 10.

[input] integer m

The number of pieces of candy.

Constraints: 2 ≤ m ≤ 100.

[output] integer

The total number of pieces of candy the children will eat provided they eat as much as they can and all children eat the same amount.

代码

function candies(n, m) {
  if ((n > 10 || n < 1) || (m > 100 || m < 2)) {
    return 0;
  } else if (n > m) {
    return 0;
  } else if (n === m) {
    return m;
  } else if (n < m) {
    var candyKids = Math.round(m / n);
    return candyKids * n;
  };
};

最佳答案

以下是一些会因您的代码而失败的测试用例:

candies( 2, 3 ) === 2 (Your output: 4)
candies( 2, 5 ) === 4 (Your output: 6)
candies( 3, 5 ) === 3 (Your output: 6)
candies( 4, 7 ) === 4 (Your output: 8)

错误在哪里?

您使用的是 Math.round 而不是 Math.floor,这意味着您将在分配给 child 后将大于一半的部分糖果舍入,因此对于 candies( 2, 3 ),您确定每个 child 有 m/n = 1.5 颗糖果,然后对其进行四舍五入并分配 2 code> 给每个 child 糖果,但这会产生比你开始时需要的更多的糖果。在这种情况下,您需要改为地板(始终将部分糖果向下舍入)并且只给每个 child 1 糖果。

关于javascript - If 语句未通过测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110451/

相关文章:

javascript - 在 Electron 中将 HTMLtable 导出为 CSV

javascript - 在html中使用大量的javascript

java - 在 Android 中按下按钮时如何设置单选按钮的文本颜色?

r - 在 R 中使用 if else 为 for 语句的每次迭代保存值

php - 路由中的 Laravel 多个中间件具有 OR 条件

javascript - Django:检索 Ajax 调用中所选下拉选项的私钥

javascript - 如何在页面上执行函数?

javascript - 如何使用 React-Intl 插入带有 injectIntl​​ formatMessage 的 HTML 标签?

MATLAB:如何检查矩阵中的任何元素是否为 nan 并在是这种情况下执行某些操作

java - 在java中处理n个if-else if的更好方法