開啟章節選單
573 The Snail
題目連結
題目敘述
一隻蝸牛嘗試從一口井爬出來,每行包含 4 個數 H
、 U
、 D
、 F
。
H
: 井的深度U
: 白天爬升高度D
: 晚上滑落高度F
: 疲勞係數(百分比)
請模擬蝸牛每天的運動,判斷第幾天成功爬出或失敗滑落。
解題思路
用 while
迴圈模擬, height
紀錄目前爬升高度, up
紀錄白天爬升高度,每次天數加一並更新 height
、 up
。
程式碼
#include <bits/stdc++.h> using namespace std; int main() { int H, U, D, F; while (cin >> H >> U >> D >> F && (H || U || D || F)) { double height = 0, up = U; int day = 0; string success = "failure"; while (height >= 0) { day += 1; height += up; up -= U * F / 100.0; if (up < 0) up = 0; if (height > H) { success = "success"; break; } height -= D; } cout << success << " on day " << day << '\n'; } }