練習17.31
對于本節中的遊戲程式,如果在do循環内定義b和e,會發生什麼?
解答:
#include <iostream>
#include <random>
#include <string>
using namespace std;
int main(){
string resp;
//default_random_engine e;
//bernoulli_distribution b;
do{
default_random_engine e;
bernoulli_distribution b;
cout << e() << endl;
cout << b(e) << endl;
bool first = b(e);
cout << (first? "We go first" : "You get to go first") << endl;
//cout << ((play(first))? "Sorry, you lost" : "congrats, you won") << endl;
cout << "play again? Enter 'yes' or 'no'" << endl;
} while(cin >> resp && resp[0] == 'y');
}
可以嘗試這樣寫代碼進行驗證。
b放在循環内部,或者循環外部都是可以的。
但是,當把e的聲明放在循環内部的話,每次生成的數就一樣了。放在循環外部e就能保持狀态,每次都會生成不同的随機數。
練習17.32
如果我們再循環内部定義resp,會發生聲明?
解答:
這個很容易看出來。編譯階段就會出現問題。
在while語句中肯定會提示resp沒有定義。
練習17.33
修改11.3.6節(第392頁)中的單詞轉換程式,允許你對一個給定單詞有多種轉換方式,每次随機選擇一種進行實際轉換。
解答:
這個就略過吧。
用随機數操作來進行選擇對應的轉換即可。