Vb.net VB将长度从英制转换为公制

Vb.net VB将长度从英制转换为公制,vb.net,visual-studio-2010,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 = t

您好,我正在尝试将英寸转换为厘米,英里和英尺转换正确,但厘米返回的值为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"    

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

当然,如果您在项目属性上使用了
选项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        

在VB中,
+
用于数学,
&
用于连接字符串。正如您的代码当前所示,
英里
英尺
英寸
都是未声明的,因此这甚至不会编译。如果它们在其他地方声明,但未设置,则输出将为0。@有一天:VB.net允许,请尝试:
Dim a As String=“abc”Dim b As String=“def”Debug.Print(a+b)
@Bluedog VB允许的和明智的做法是两件不同的事情
Dim a=“21”Dim b=21 Dim c=a+b
(选项关闭)@史提夫:是的,我从没说过这是明智的谢谢你,史蒂夫,我感谢你的帮助。我也很感谢你关于开启选项的建议。很高兴能帮上忙。作为网站的新用户,如果这个答案解决了您的问题,我建议您阅读