You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中0 < CInt(Num(x)) < 10比较语句失效问题求助

VB条件判断始终返回True的原因及修复

核心错误原因

你写的If 0 < CInt(Num(x)) < 10这种连续比较写法,VB是不支持的。它会被拆解成两步计算:

  1. 先计算0 < CInt(Num(x)),不管输入的是90还是9000000,这个表达式都会返回True
  2. 再把第一步的结果(True)和10比较,VB里布尔值True会被转换成数值-1,-1 < 10显然成立,所以整个条件永远返回True

修复方案

把连续比较拆成两个独立条件,用And连接:

If CInt(Num(x)) > 0 And CInt(Num(x)) < 10 Then

额外的代码优化建议

  1. 变量声明问题:Dim Num(2), INPUT As String中,只有INPUT是String类型,Num数组默认是Variant类型,建议明确声明类型:
    Dim Num(2) As String, INPUT As String
    
  2. 输入方式混用:代码里同时用了MsgBox和Console.ReadLine,建议统一成一种,比如都用控制台输入输出:
    Console.WriteLine("Please enter a number")
    Num(x) = Console.ReadLine()
    
  3. 无限循环问题:外层While Cond = False循环里,Cond始终是False,会导致程序一直重复弹出"All three numbers are valid",可以在循环内设置Cond = True来终止循环,或者直接去掉外层循环。

修复后的完整代码示例

Dim Num(2) As String, INPUT As String
Dim Cond As Boolean = False
Dim Valid As Boolean = False
Dim Isnum As Boolean
Dim x, Number, IsTen As Integer

While Cond = False
    Do Until IsTen = 3 And Number = 3
        IsTen = 0
        Number = 0
        For x = 0 To 2
            Console.WriteLine("Please enter a number")
            Num(x) = Console.ReadLine()
            Isnum = IsNumeric(Num(x))
            If Isnum = True Then
                IsTen = IsTen + 1
            End If
            If Isnum = True Then
                ' 修复后的条件判断
                If CInt(Num(x)) > 0 And CInt(Num(x)) < 10 Then
                    Number = Number + 1
                End If
            End If
        Next
        If Number <> 3 Then
            Console.WriteLine("Sorry all three numbers werent between 0 and 10, Please enter again")
        End If
        If IsTen <> 3 Then
            Console.WriteLine("Sorry all three inputs werent numbers, Please enter again")
        End If
    Loop
    Console.WriteLine("All three numbers are valid")
    ' 添加终止循环的条件
    Cond = True
End While

内容的提问来源于stack exchange,提问作者Noe Topalian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:18:27