【发布时间】: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:null和x2:1例如,结果会给你null -
@Sajid 同意。我的意思是使用
float.TryParse是最好的方法。但是,如果 OP 希望拥有null值,那么他可以使用我提到的方式。在这种情况下,我更喜欢使用var xdiff = x1 - x2。
标签: c# floating-point