gpt4 book ai didi

javascript - 相同的生日概率代码值不是预期的

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:00 25 4
gpt4 key购买 nike

有一个名为 Same Birthday Probabilty 的代码战挑战挑战是:

Given n number of people in a room, calculate the probability that any two people in that room have the same birthday (assume 365 days every year = ignore leap year). Answers should be two decimals unless whole (0 or 1) eg 0.05

我为这个挑战做了以下工作:

function calculateProbability(n){
var result = 0;
for(i=1;i<n;i++){
var total = (365 - i) / 365
result = result * total
}
return Math.round(result)
}

使用和不使用 Math.round 方法,但我总是得到:

✘ Value is not what was expected enter image description here

and that is the only error.

这就是测试用例

Test.expect(calculateProbability(5)==0.03);
Test.expect(calculateProbability(1000)==1);

最佳答案

首先,您应该将结果更改为 1,因为乘以 0 的结果始终为零。您正在计算的结果是解决方案的补充,它是 n 人生日不同的概率。最后,您没有将数字四舍五入到小数点后两位。

function calculateProbability(n){
var result = 1;
for(i=1;i<n;i++){
var total = (365 - i) / 365
result = result * total
}
return Math.round((1-result)*100 )/100
}

关于javascript - 相同的生日概率代码值不是预期的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39666155/

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