这是我在Visual C ++上的Q& A游戏的代码
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!!");
}
有没有缩短此代码?考虑使用数组?
答案 0 :(得分: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!!");
答案 1 :(得分: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!!");
答案 2 :(得分:0)
尝试使用switch case
声明。