gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:26:51 26 4
gpt4 key购买 nike

您好,我正在处理 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com