cm到inch转换器,两个文本框相乘一个值

时间:2010-11-08 20:34:13

标签: c# asp.net

我在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"
}

3 个答案:

答案 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);
}

<强>算法

  1. 验证用户是否在每个TextBox es中输入了一个int可解析字符串;
  2. 构建表示盎格鲁 - 撒克逊测量值的字符串,然后将其相乘以进行转换(正如您在样本中所做的那样);
  3. Result Label;
  4. 中显示结果
  5. 将结果格式化为anglo-saxon测量单位,以便输出相应的TextBox
  6.   

    <强>声明

         

    这段代码没有编译,而是直接写在我的头顶。因此,为了正确编译并具有正确的预期行为,可能需要进行微小的更改。

    这有帮助吗?