vb.net - 困惑为什么数字之间的比较返回 true

标签 vb.net if-statement

我使用以下代码来检查我的健康状况是否超出允许的最大健康状况:

    Public Sub healthCheck()

    If Player.CurrentHealth > Player.MaxHealth Then
        MsgBox(Player.CurrentHealth & "&" & Player.MaxHealth)
        Player.CurrentHealth = Player.MaxHealth
        MsgBox(Player.CurrentHealth & "&" & Player.MaxHealth)

    ElseIf (0 > Player.CurrentHealth) Then

        Player.CurrentHealth = 0

    End If

End Sub

我添加了消息框用于调试目的,它们输出以下字符串:

第一个消息框 = 8&20

第二个消息框 = 20&20

如果第一个告诉我

currenthealth = 8 

maxhealth = 20

为什么它甚至进入 if 结构? 据我所知,8不高于20

编辑:

这似乎只发生在 10 马力以下!因此,对于 10/20,它不会输入 if,只是跳过 if 结构,但是在 9/20,它会重置为 20/20(就好像比较返回 true)

最佳答案

您的健康变量可能是字符串:

MsgBox("8" > "20") // Outputs True

正确的是

Dim currentHealth As Int32 = Int32.Parse(Player.CurrentHealth)
Dim maxHealth As Int32 = Int32.Parse(Player.MaxHealth)

If currentHealth > maxHealth Then
    MsgBox(currentHealth & "&" & maxHealth)
    Player.CurrentHealth = PLayer.MaxHealth
    currentHealth = maxHealth
    MsgBox(currentHealth & "&" & maxHealth)

ElseIf (0 > currentHealth) Then

    Player.CurrentHealth = 0

End If

关于vb.net - 困惑为什么数字之间的比较返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813993/

相关文章:

vb.net - string() 类型的值无法转换为字符串

c# - 使用 vb 返回 IEnumerable 时,Asp.net 4.5 模型绑定(bind)中断?

asp.net - 使用 asp.net (VB) 从 MySQL 中选择、更新、插入和删除的脚本?

java - 我的代码不能正常工作? IF 语句多个类

java - 用设计模式替换多个 If\Else

javascript - 使用条件语句在 Javascript 中的不同 for 循环之间进行选择

javascript - 不使用 isNan 的简单条件?

vb.net - 后台 worker 不起作用... VB.Net

vb.net - Visual Basic - 使用数组和 For 循环的随机数生成器

c - 程序未检测 if 语句