首页 > 试题广场 >

牛牛掷硬币

[编程题]牛牛掷硬币
  • 热度指数:563 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
掷了n次硬币,如果这n次硬币全部朝上或者全部朝下的概率是多少?(每次掷硬币朝上的概率与朝下的概率相同)

示例1

输入

1

输出

"1.00"

说明

概率为1,四舍五入保留两位小数的字符串为"1.00" 
示例2

输入

5

输出

"0.06"

说明

概率为0.0625,四舍五入保留两位小数的字符串为"0.06" 

备注:

对于的数据:

对于的数据:
对于每个n,返回一个严格四舍五入保留两位小数的字符串。
比如概率为0.372的话,返回字符串"0.37"。
概率为0.957的话,返回字符串"0.96"。
(注意,返回的字符串不带引号)
加了一个小的数来保证第三位是5时,保留两位小数一定能够严格四舍五入上来
class Solution:
    def Probability(self , n ):
        # write code here
        res = str(round(0.5**n * 2 + 0.0005, 2))
        return res + '0'*(res.index('.') + 3 - len(res))

发表于 2021-05-23 16:57:05 回复(0)
class Solution:
    def Probability(self , n ):
        # write code here
        if n >= 1000:
            return '0.00'
        def qpow(x,y):
            ans = 1
            while y:
                if y & 1:
                    ans *= x
                y //= 2
                x *= x
            return ans
        eps = 1e-7
        return str(format(2 / qpow(2,n) + eps,'.2f'))

发表于 2021-08-27 18:03:47 回复(0)
Decimal四舍五入
class Solution:
    def Probability(self , n ):
        # write code here
        from decimal import Decimal
        a = 0.5 ** n * 2
        ans = Decimal(a).quantize(Decimal('0.01'), rounding="ROUND_HALF_UP")
        return str(ans)


编辑于 2021-07-06 13:19:07 回复(0)
class Solution {
public:
    /**
     * 返回一个严格四舍五入保留两位小数的字符串
     * @param n int整型 n
     * @return string字符串
     */
    string Probability(int n) {
        // write code here
        if(n == 1){
            return "1.00";
        }
        int m = pow(0.5, n) * 2000;
        if(m % 10 >= 5){
            m = m / 10 + 1;
        } else{
            m = m / 10;
        }
        string res = "0.00";
        if(m < 10){
            res[3] = m + '0';
        } else{
            res[3] = m % 10 + '0';
            m /= 10;
            res[2] = m + '0';
        }
        return res;
    }
};

发表于 2021-03-07 10:57:19 回复(0)

问题信息

难度:
4条回答 1286浏览

热门推荐

通过挑战的用户

查看代码