循环!循环!循环!——洛谷#P1423 小玉在游泳(Python实现)

题目描述

小玉开心的在游泳,可是她很快难过的发现,自己的力气不够,游泳好累哦。已知小玉第一步能游2米,可是随着越来越累,力气越来越小,她接下来的每一步都只能游出上一步距离的98%。现在小玉想知道,如果要游到距离x米的地方,她需要游多少步呢。请你编程解决这个问题。

Python题解

解答1 

  • 使用等比数列求和,将a1=2,q=0.98代入以下公式。
  • Sn为输入的目标距离,n为待求的步数。
  • 用Python 中的 ceil 函数向上取整。

# -*- coding: utf-8 -*-
# @Time    : 2019/10/31 17:27
# @Author  : 小晓酱
# @File    : luoguu.py
# @Software: PyCharm

import math
Distance = float(input())
Step = math.ceil(math.log(1 - Distance / 100) / math.log(0.98))
print(Step)

解答2

  • 常规解法,求和。比较之后,输出步数。
# -*- coding: utf-8 -*-
# @Time    : 2019/10/31 17:27
# @Author  : 小晓酱
# @File    : luoguu.py
# @Software: PyCharm

Distance = float(input())
Sum = 0
Step = 0
while Sum < Distance:
    Sum += 2 * (0.98 ** Step)
    Step += 1
print(Step)
发布了330 篇原创文章 · 获赞 71 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/sinat_26811377/article/details/102875378