01003: Hangover
math , http://cs101.openjudge.cn/practice/01003
How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below.

输入
The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits.
输出
For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples.
样例输入
1.00
3.71
0.04
5.19
0.00样例输出
3 card(s)
61 card(s)
1 card(s)
273 card(s)来源
Mid-Central USA 2001
浮点数与0比较需要 用 math.isclose(....),而不能直接用 == 0.00判断。
在程序中,比较浮点数和0直接相等是不太可靠的。这是因为浮点数在计算机中以二进制表示,并且存在舍入误差。由于舍入误差,浮点数的精确表示可能会有微小的偏差。
当我们比较浮点数和0时,实际上是在比较它们的偏差是否小于某个误差范围。如果我们直接使用==运算符或类似的比较操作符进行比较,可能会由于舍入误差的存在而得到意想不到的结果。
为了解决这个问题,通常我们可以使用一个误差范围(通常称为“容差”或“epsilon”)来进行浮点数比较。例如,如果我们想要比较浮点数x是否接近0,可以使用以下方式进行比较:abs(x) < epsilon,其中epsilon是一个很小的正数,代表我们容忍的最大误差范围。
为了更准确地进行浮点数的比较,可以使用math.isclose()函数或自定义的比较函数,这些函数允许你指定一个容差值来比较浮点数的接近程度。这些函数会考虑到舍入误差,并提供更可靠的浮点数比较方式。因此,在重要的精确度要求下,建议使用这些比较方法来避免舍入误差带来的问题。
总之,浮点数比较时要小心舍入误差,最好使用误差范围进行比较,而不是直接使用等于或不等于操作符。
import math
while True:
n = float(input())
if math.isclose(n, 0.00, rel_tol=1e-5) :
break
cnt = 0
tot = 0
while True:
cnt += 1
tot += 1/(1+cnt)
if tot>n:
break
print(cnt, "card(s)")