1

这是我在 Visual C++ 上的问答游戏的代码

             if (this->answer->Text == "2"){
                 this->question->Text = "2+2?";
             }
             else if (this->answer->Text == "4"){
                 this->question->Text = "3+3?";
             }
             else if (this->answer->Text == "6"){
                 this->question->Text = "4+4?";
             }
             else if (this->answer->Text == "8"){
                 this->question->Text = "Finished!";
             }
             else {
                 MessageBox::Show("Wrong!!");
             }

有什么可以缩短此代码吗?考虑使用数组?

4

3 回答 3

2

我不是 Windows 程序员,不知道你的类型 this->question->Text是什么,你没有告诉我们,但如果是std::string或可以转换为的东西char *,那么这应该可以工作:

std::string t = this->answer->Text;
this->question->Text = t == "2" ? "2+2?"
                     : t == "4" ? "3+3?"
                     : t == "6" ? "4+4?"
                     : t == "8" ? "Finished"
                     : "";
if (this->question->Text = "") MessageBox::Show("Wrong!!");
于 2012-12-10T16:45:57.343 回答
1

你在重复if (this->answer->Text ==this->question->Text =。只写一次并将条件和答案保存在 std::map 中。

更新:

#include <map>
#include <string>

...

std::map<std::string,std::string> answers;
answers["2"]="2+2"; // "configuration
answers["4"]="3+3?";
//and so on
std::string text=this->answer->Text;
    // instead of if ...
std::map<std::string,std::string>::const_iterator found=answers.find(text);
if (found!=answers.end())
    this->question->Text = answers[text]; //once. Even better found->second
else
    MessageBox::Show("Wrong!!"); 
于 2012-12-10T16:42:24.623 回答
0

尝试使用switch case语句。

于 2012-12-10T16:40:07.267 回答