0

私はC#を初めて使用しますが、このコードの何が問題になっているのか理解できません。私はクイズを作成していて、答えが正しければよくできていると言おうとしていますが、文字列型をbool型に暗黙的に変換することはできません。

これが私のコードです:

{
    int score = 0;
    Console.WriteLine(" What is your name?");
    string name = "";
    name = Console.ReadLine();

    Console.WriteLine("Hello " +name+ " and welcome to the Formula 1 quiz.");
    Console.ReadLine();

    Console.WriteLine("Question 1: How many races has Michael Schumacher won.");
    Console.ReadLine();

    Console.WriteLine("a) 91");
    Console.WriteLine("b) 51");
    Console.WriteLine("c) 41");
    Console.WriteLine("d) 31");

    Console.ReadLine();
    string answer = Console.ReadLine();

    if (answer = a) Console.WriteLine("Well done");
    else Console.WriteLine("Wrong answer");
}
4

2 に答える 2

6

変化する:

if (answer =  a)

if (answer ==  "a")
于 2013-01-20T17:24:43.647 に答える
2

ここでのステ​​ートメントでは、代入演算子(=)を使用しています。if

if (answer =  a)

見た目から、入力内容を文字列と比較したいaので、最初に比較演算子(==)を使用して、実際に文字列と比較する必要があります。

if (answer == "a")
    Console.WriteLine("Well done");
else
    Console.WriteLine("Wrong answer");

Visual Studio(または使用しているIDE)は、a宣言されていない(またはbool)ので、実際にこれを取得する必要があります。


上記はすでに回答されているので、関係のないメモでは、宣言と割り当てを分離する必要がないため、ここで変数の宣言と割り当てを同じ行に変更できます。

string name = "";
name = Console.ReadLine();

に:

string name = Console.ReadLine();
于 2013-01-20T17:26:26.737 に答える