POJ 1003 Hangover
Description
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.
![](http://poj.org/images/1003/hangover.jpg)
Input
Output
Sample Input
1.00 3.71 0.04 5.19 0.00
Sample Output
3 card(s) 61 card(s) 1 card(s) 273 card(s)
Source
题目大致意思:就是你有很多卡片,然后重叠的放在一起,重叠的规则是:第一张卡片伸出桌面的1 / 2,第二张1 / 3,第三张1 / 4……依次类推第n张1 / (n + 1)。
现在给出伸出桌面的长度,问你最少需要几张卡片才能达到要求。
其实很简单,就是一个循环,每次sum加1 / (i + 1),当sum >= 给出的长度的时候就跳出循环,然后输出i就好。
代码如下:
#include<iostream> using namespace std; int main() { int i; double sum, n; while (cin >> n&& n) { sum = 0; for (i = 1;; i++) { sum += 1.0 / (i + 1); if (sum >= n) break; } cout << i << "card(s)" << endl; } }