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它是未声明的(或 a bool)。


在一个不相关的注释中,因为上述问题已经得到解答,您可以在此处将变量声明和赋值更改为在同一行,因为不需要将声明和赋值分开。

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

至:

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