【问题标题】:"Cannot implicitly covert type float? to float"“不能隐式转换类型浮点数?到浮点数”
【发布时间】:2020-03-02 22:07:13
【问题描述】:

我正在尝试减去浮点格式的 2 个变量(float xdiff = x1 - x2;),但是我收到错误“不能隐式转换类型浮点数?要浮点数”。 d,c,s,m,radius,x1,y1,x2,y2 的值是从 windows 窗体输入中获得的。

代码如下;

    public Nullable<float> d = null;

    public Nullable<float> c = null;

    public Nullable<float> s = null;

    public Nullable<float> m = null;

    public Nullable<float> radius = null;

    public Nullable<float> x1 = null;

    public Nullable<float> y1 = null;

    public Nullable<float> x2 = null;

    public Nullable<float> y2 = null;



private void Run_Click(object sender, EventArgs e)
        {
            d = float.Parse(this.downwind.Text);
            c = float.Parse(this.crosswind.Text);
            s = float.Parse(this.maxcross.Text);
            m = float.Parse(this.offset.Text);
            radius = float.Parse(this.rad.Text);
            x1 = float.Parse(this.x1coord.Text);
            y1 = float.Parse(this.y1coord.Text);
            x2 = float.Parse(this.x2coord.Text);
            y2 = float.Parse(this.y2coord.Text);

            float xdiff = x1 - x2;


        }

【问题讨论】:

  • 不要使用float.Parse,因为Text不能转换为float会抛出异常,请改用float.TryParse
  • @Sajid 谢谢。我会实现的
  • 你应该使用float? xdiff = x1 - x2;
  • @MKR,如果x1:nullx2:1 例如,结果会给你null
  • @Sajid 同意。我的意思是使用float.TryParse 是最好的方法。但是,如果 OP 希望拥有 null 值,那么他可以使用我提到的方式。在这种情况下,我更喜欢使用var xdiff = x1 - x2

标签: c# floating-point


【解决方案1】:

如果x1x2 的类型应该是float?,那么x1 - x2 的运算结果可以是null(如果以太值是null)。因此,结果应存储在float? 中。 Nullable value types

你应该使用

float? xdiff = x1 - x2;

或者最好是:

var xdiff = x1 - x2;  //Using var will automatically decide type of result 

【讨论】:

  • 记住使用float? 是有效的,但结果应该存储在匹配类型中。因为说40.0 - null = null
【解决方案2】:

假设您处理所有 NULL 场景,下面应该可以解决它。

float xdiff = (x1 - x2).Value;

【讨论】:

  • 谢谢。它确实解决了它。你能向我解释为什么这有效吗?非常感谢:)
  • 那么浮点数和浮点数的区别? (或 Nullable)是后者允许您保存空值,而 float 没有空值。为了优雅地(在 CLR 的观点中)处理这个问题,Nullable 是一个提供 .HasValue 和 .Value 等属性的包装器。在 MSDN 上阅读它。
  • 请注意,这仅在 x1x2 不为空时有效。如果它们不为 null,则根本没有理由使用 float?
  • @DourHighArch 你是对的。 OP 已将 x1x2 声明为 Nullable float。因此,在更正声明之前,这将不起作用。
  • if (x1.HasValue == true &amp;&amp; x2.HasValue == true &amp;&amp; y1.HasValue == true &amp;&amp; y2.HasValue == true &amp;&amp; m.HasValue == true) 我已经使用它来确保处理 Null 场景。 @MKR 你的解决方案也有效。
猜你喜欢
  • 2011-02-02
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2013-09-12
  • 1970-01-01
相关资源
最近更新 更多