我在C#中制作一个厘米到英尺/英寸的转换器有问题,这就是得到的:
<asp:textbox id="txtFoot" runat="server"></asp:textbox>
<asp:textbox id="txtInches" runat="server"></asp:textbox>
<asp:Button id="btnAdd" runat="server" text="Count" onclick="btnAdd_Click" />
<br />
<asp:Label ID="lblResult" runat="server"></asp:Label>is<asp:Label ID="lblFootAndInches" runat="server"></asp:Label>cm
<%--I try to get a result "10'1" is 3,939 cm"--%>
protected void btnAdd_Click(object sender, EventArgs e)
{
lblResult = (txtFoot.Text + "," + txtInches.Text) * 0,39; //I would like to get 10,1 * 0,39 = 3,939 (10 foot and 1 inch)
lblFootAndInches = txtFoot.Text + "'" + txtInches.Text + '"'; //I'm looking for a result like 10'1"
}
答案 0 :(得分:3)
我不知道ASP.NET,但我想我可以处理这段代码......
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
lblResult.Text = (Double.Parse(txtFoot.Text + "," + txtInches.Text) * 0.39).ToString();
lblFootAndInches.Text = txtFoot.Text + "'" + txtInches.Text + "\"";
}
catch (FormatException s)
{
//Do some exception handling here, like warning the viewer to enter a valid number.
}
}
我希望这有帮助!
答案 1 :(得分:2)
您的代码中存在多个错误。您还需要消除有关全球化和区域选项的问题(系统是否使用,或。作为小数点字符,我建议将代码更改为以下内容:
string separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
txtFoot.Text = txtFoot.Text.Replace(".", separator).Replace(",", separator);
txtInches.Text = txtInches.Text.Replace(".", separator).Replace(",", separator);
Double result = (Double.Parse(txtFoot.Text) * 30.48) + (Double.Parse(txtInches.Text) * 2.54);
lblResult.Text = result.ToString();
lblFootAndInches.Text = string.Format("{0}'{1}\"", txtFoot.Text, txtInches.Text);
如果您不需要担心区域设置,请跳过前三行代码。
希望这有帮助。
答案 2 :(得分:0)
我建议如下:
protected void btnAdd_Click(object sender, EventArgs e) {
int feet = 0;
int inches = 0;
if (!int.TryParse(txtFoot.Text, out feet))
throw new FormatException(string.Format("{0} is not a valid value", txtFoot.Text));
if (!int.TryParse(txtInches.Text, out inches))
throw new FormatException(string.Format("{0} is not a valid value", txtInches.Text));
double meters = ((double)(string.Format("{0}.{1}", feet, inches)) * .39;
lblResult.Text = string.Format("{0}", meters);
lblFootAndInches.Text = string.Format("{0}'{1}\"", feet, inches);
}
<强>算法强>
TextBox
es中输入了一个int可解析字符串; Result Label
; TextBox
。<强>声明强>
这段代码没有编译,而是直接写在我的头顶。因此,为了正确编译并具有正确的预期行为,可能需要进行微小的更改。
这有帮助吗?