【问题标题】:Why when i change float to 1 it shows error CS0029 [closed]为什么当我将浮点数更改为 1 时它显示错误 CS0029 [关闭]
【发布时间】:2021-10-11 15:44:11
【问题描述】:

我正在尝试用 c# 创建一个迷你游戏,当我希望浮点数为 1 时,会显示错误 错误 CS0029 无法将类型“int”隐式转换为“bool”。

    class Program
{
    static void Main(string[] args)
    {
        bool x = 1;
        while (x = 2) ;
        Console.ReadLine()
    }
}

【问题讨论】:

  • 您的问题是关于 float,但在您的代码中没有任何迹象 - 相反,您有一个 bool 类型的变量,它的值只能是 truefalse.
  • 您试图将2 分配给x 变量,这是不允许的,因为while 循环等待bool 值。要比较它,请使用双等号 ==: while (x == 2) { ... }
  • 还要注意while (x = 2) 应该是while (x == 2),但是你仍然有一个紧密的循环......
  • 我在这里有点猜测,但也许您打算将 x 声明为整数(既不是 float 也不是 bool)。如果是这样,请尝试int x = 1;
  • @Manu 你的回答很有帮助。谢谢。

标签: c# compiler-errors


【解决方案1】:

大概应该是这样的:

class Program
{
    static void Main(string[] args)
    {
        int x = 1; // not 'bool x'

        while (x != 2)
        { 
           // Loop runs...
           
           // And at some time:
           x = 2;
           // And loop breaks
        }

        Console.ReadLine()
    }
}

【讨论】:

  • 你的回答也很有帮助,就像@Manu 的一样。
猜你喜欢
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2012-11-02
  • 2020-01-31
  • 2018-05-13
  • 1970-01-01
  • 2023-01-31
相关资源
最近更新 更多