【问题标题】:C# converting type double to floatC#将double类型转换为float
【发布时间】:2018-01-02 22:22:37
【问题描述】:

我是 C# 新手,我不知道为什么我在这些代码行中收到以下错误。

“错误 CS0266:无法将类型 'double' 隐式转换为 'float'。存在显式转换(您是否缺少强制转换?)”

float rightEdgeOfFormation = (float) transform.position.x + (width * 0.5);
float leftEdgeOfFormation = (float) transform.position.x - (width * 0.5);

我认为写作(浮动)是演员?

非常感谢!

【问题讨论】:

  • 我认为这只是你的括号。 float rightEdgeOfFormation = (float) (transform.position.x + (width * 0.5));
  • 请记住,当你写一些像0.5 这样的想法时,它会被解释为double 值,如果你希望它是float,请将f 添加到0.5f 这样的数字末尾。

标签: c# unity3d types


【解决方案1】:

您乘以 0.5,当您使用浮点数时,您需要将 f 放在末尾。

这将起作用:

float rightEdgeOfFormation = transform.position.x + (width * 0.5f);
float leftEdgeOfFormation = transform.position.x - (width * 0.5f);

【讨论】:

  • 没问题 - 每个人都会遇到这种情况,请务必接受我的正确答案:)
  • 最佳答案。无需投射任何东西,或使用我在一个答案中看到的丑陋的 Convert.ToSingle() 。始终考虑在您的号码上使用正确的后缀。
【解决方案2】:

试试:

float rightEdgeOfFormation = (float) (transform.position.x + (width * 0.5));
float leftEdgeOfFormation = (float) (transform.position.x - (width * 0.5));

您只是在转换 transform.position.x 而不是整个表达式 & 表达式中的其他内容导致计算以双精度形式完成。

【讨论】:

    【解决方案3】:
    float rightEdgeOfFormation = (float)transform.position.x + ((float)width * 0.5F);
    float leftEdgeOfFormation = (float)transform.position.x - ((float)width * 0.5F);
    

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/float

    【讨论】:

    • 对我来说,widthtransform.position.xtransform.position.y 不是双打还不清楚。这也是我在其中放演员表的原因。
    【解决方案4】:

    我认为这只是你的括号。 float rightEdgeOfFormation = (float) (transform.position.x + (width * 0.5));

    【讨论】:

      【解决方案5】:

      使用下面的

      float rightEdgeOfFormation = Convert.ToSingle(transform.position.x + (width * 0.5));
      

      float leftEdgeOfFormation = Convert.ToSingle(transform.position.x - (width * 0.5));

      【讨论】:

      • 在调用 Convert 之前,您如何考虑将其转换为字符串,以确保获得更糟糕的解决方案?
      【解决方案6】:

      类型转换在所有其他操作中具有最高优先级。因此,(float) transform.position.x+ (width * 0.5) 之前进行评估。但是,(width * 0.5)double 表达式,因为常量 0.5double 常量。 (如果你希望它是float,你应该使用0.5f。)当添加floatdouble 时,C# 总是将float“提升”为double。所以,float + double 的结果是 double,然后它不能分配给 float

      要解决此问题,请在转换为 float 之前将整个表达式放在括号中,或者将 0.5 设为 float 常量,将其写为 0.5f

      【讨论】:

        猜你喜欢
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多