【问题标题】:if statement error: int conversion to booleanif 语句错误:int 转换为 boolean
【发布时间】:2015-11-09 11:23:29
【问题描述】:
public static void Main(string[] args) // this is a method called "Main". It is called when the program starts.
{

    Random numberGenerator = new Random();

    int userInput1;
    int userInput2;
    int finalUserInput;
    int theCorrectAnswer;

    //generating random numbers. from 1 to 10. 11 is exclusive.
    userInput1 = numberGenerator.Next(1, 11);
    userInput2 = numberGenerator.Next(1, 11);

    //Asks the user to solve the multiplication problem.
    Console.Write("What is " + userInput1 + " x " + userInput2 + " ?");
        finalUserInput = Convert.ToInt32(Console.ReadLine());
        theCorrectAnswer = userInput1 * userInput2;

    if(finalUserInput = theCorrectAnswer)

嗨。当我尝试设置带有条件的 if 语句时,会弹出一条错误消息,提示您无法将 int 隐式转换为 boolean。我根本不想那样做。我很迷茫。救命!

【问题讨论】:

  • 你在做finalUserInput = theCorrectAnswer,这是赋值。因此,您的 if 最终成为“if(int)”,这就是您收到该错误的原因。您应该将= 替换为==

标签: c# int boolean


【解决方案1】:

您的情况需要相等运算符 ==,但您在 if 语句中使用赋值运算符 =:

if (finalUserInput = theCorrectAnswer)

应该如下所示:

if (finalUserInput == theCorrectAnswer)

【讨论】:

    【解决方案2】:

    您正在使用单个=theCorrectAnswer 变量的值设置为finalUserInput。这个语句返回值——整数一。

    您需要使用== 来比较两个值。

    这是一个错字或语法错误。

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多