1

これは、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!!");
             }

このコードを短縮するものはありますか? 配列の使用を検討しますか?

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 に答える