我的任務是創建一個小拼字游戲,我的一項“微”任務是根據帶有與點關聯的字母的圖表計算給定單詞的分數:
點信
1:a、e、i、l、n、o、r、s、t、u
2:d,g
3: b, c, m, p
4: f, h, v, w, y
5:k
8: j, x
10:q,z
無論如何,我的第一個想法就是遍歷給定的單詞并使用 if 回圈檢查每個字母。
for(auto ch: word){
// as an example this if loop would check if the letter the for loop is on is an 'a' or 'e' or ....
// and then adds 1 point to integer 'score' as defined by the bale above
if(ch == a || ch == e || ch == i || ch == l){
score = score 1;
}
}
所以我的問題是,是否有更簡潔的方法來制作 if 回圈?類似的東西:if(ch == a,e,i,l...) 類似的東西?對于我的任務,我只被允許使用 c 17,但我對 c 相當陌生,并沒有意識到它的最大潛力。希望你們中的一位能告訴我什么是可能的。謝謝
uj5u.com熱心網友回復:
撰寫一個函式來計算值,并用switch陳述句實作它:
Int score(char ch) {
switch(ch) {
case ‘a’:
case ‘e’:
case ‘i’:
// etc.
return 1;
case ‘d’:
case ‘g’:
return 2;
// and so on …
}
}
編譯器將為此生成有效的代碼。它適用于任何字符編碼,并且可以輕松擴展為更豐富的字符集。它將使用比 an 少得多的記憶體,unordered_map并且幾乎肯定會更快。
uj5u.com熱心網友回復:
由于您擁有字母表中的所有字符,您可以擁有一個字符值陣列,使用字符作為偏移量:(注意在這種情況下,映射是 A->J 是 1 點,K 和 L 是 2 點等。你必須調整你的點的映射。)
int point_mapping[] =
{
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2,
3, 3, 3, 3,
4, 4, 4, 4, 4,
5,
8, 8,
10, 10
};
for (auto& ch : word)
{
score = point_mapping[tolower(ch) - 'a'];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335947.html
