VB将长度从英制转换为公制

时间:2014-10-11 20:26:23

标签: vb.net visual-studio-2010

您好我正在尝试将英寸转换为厘米,英里和英尺正确转换,但厘米返回值0.任何有关我可能遇到此问题的建议吗?

Dim totalInches, totalMeters As Long
    Dim km, m As Double
    Dim cm As Decimal
    Dim result As String

    totalInches = 63360 * miles + 36 * yards + 12 * feet + inches
    totalMeters = totalInches / 39.37
    km = Int(totalMeters / 1000)
    m = Int(totalMeters - (km * 1000))
    cm = (totalMeters - (km * 1000) - m) * 100

    result = "The Metric Length is:" + vbNewLine _
        + km.ToString + " Kilometers" + vbNewLine _
        + m.ToString + " Meters" + vbNewLine _
        + cm.ToString + " Centimeters"    

1 个答案:

答案 0 :(得分:1)

在totalInches和常量39.37之间进行除法时,使用的是Long整数。这有效地截断了结果的小数部分。

当然,如果您在项目属性上使用了Option Strict On,那么您将永远不会遇到此错误,因为您的代码无法编译。

在任何一种情况下,您都需要进行两次更改

Public Function ConvertImperialToMetric(miles as Integer, yards as Integer, feet as Integer, inches as Integer) as String

    Dim totalInches as Long

    ' totalMeters should be a double
    Dim totalMeters As Double
    Dim km, m As Double
    Dim cm As Double
    Dim result As String

    totalInches = 63360 * miles + 36 * yards + 12 * feet + inches

    ' With totalMeters as Double you don't loose the decimal part of the division
    totalMeters = totalInches / 39.37
    km = Int(totalMeters / 1000)
    m = Int(totalMeters - (km * 1000))
    cm = (totalMeters - (km * 1000) - m) * 100

    result = "The Metric Length is:" + vbNewLine _
        + km.ToString + " Kilometers" + vbNewLine _
        + m.ToString + " Meters" + vbNewLine _
        + cm.ToString + " Centimeters"    
    return result
End Function