[原創題]來猜數字 - 提示、題解
GuguGagaOJ #5 來猜數字
[原創題]來猜數字 - 提示、題解
題目簡介
製作一個猜數字機器人,首先輸入答案,接著小明會猜數字,跟他說猜大了,猜小了,還是猜對了。重複直到猜對為止。
提示
推薦打開之後想想看再繼續,不要一次使用全部
提示1
看起來似乎要讓他重複運作,肯定是迴圈了。但是要使用哪種迴圈呢?
提示2
要重複到什麼時候為止?
題解
點開會有完整解答,請想過後再開喔
思路
這題會先輸入一個整數代表答案,我們應該要讓使用者猜到正確為止,也就是如果不正確則需要一直重複,針對這種狀況,可以使用while迴圈協助程式撰寫。對於每次輸入,使用if判斷應該輸出什麼,記得換行!
完整程式碼
請注意,本程式碼僅供寫法上參考,直接複製貼上程式碼會導致你學不到任何東西。
C++ 範例程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
#define raymondwengcode ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
int main() {
raymondwengcode;
int n, g;
cin >> n >> g;
int cnt = 1;
while (n != g) {
if (n > g) {
cout << 2 << "\n";
}else {
cout << 3 << "\n";
}
cnt++;
cin >> g;
}
cout << 1 << "\n" << cnt;
return 0;
}
Python 範例程式碼
1
2
3
4
5
6
7
8
9
10
n, g, cnt = int(input()), int(input()), 1
while n != g:
if n > g:
print(2)
else:
print(3)
g = int(input())
cnt+=1
print(1)
print(cnt)
本文章以
CC BY 4.0
授權