用于下一个循环Visual Basic



我正在尝试创建一个程序,将两个用户输入的数字之间的所有数字相加。然而,我的程序似乎正在打印下面的1个数字,我根本无法计算出来。任何帮助都将不胜感激。

Dim minNum As Integer
Dim maxNum As Integer
Dim runningCount As Integer
Dim total As Integer
Dim Cont As Integer
minNum = InputBox("please input the lower number, between 1 and 100")
maxNum = InputBox("Please input the higer number, between 1 and 100")
For Cont = minNum To (maxNum - 1)
runningCount = runningCount + 1
total = total + (minNum + runningCount)
Next Cont
MsgBox(total)

不确定你想做什么。但为了理解结果数字的含义,你可以使用一个字符串变量来保存所有内部计算。我为此创建了一个变量totalLog

Dim minNum As Integer
Dim maxNum As Integer
Dim runningCount As Integer
Dim total As Integer
Dim Cont As Integer
Dim totalLog As String
minNum = InputBox("please input the lower number, between 1 and 100")
maxNum = InputBox("Please input the higer number, between 1 and 100")
For Cont = minNum To (maxNum - 1)
runningCount = runningCount + 1
total = total + (minNum + runningCount)
totalLog = totalLog & "+" & (minNum + runningCount)
Next Cont
MsgBox (total)
totalLog = totalLog & "=" & total
MsgBox (Right(totalLog, Len(totalLog) - 1))

现在,例如,如果你选择数字10和15作为较低和较高的数字,你会看到一个对数字符串"0";11+12+13+14+15=65〃;。所以较低的数字不包括在这个总数中,但较高的数字包括在内。也许这就是你困惑的原因。

作为一个小建议,我不会在这里使用额外的runningCount变量,因为您已经有了Cont计数器。以下是如何更改程序,以便添加起始&结束编号包括这些编号:

Dim minNum As Integer
Dim maxNum As Integer
Dim total As Integer
Dim Cont As Integer
minNum = InputBox("please input the lower number, between 1 and 100")
maxNum = InputBox("Please input the higer number, between 1 and 100")
For Cont = minNum To maxNum
total = total + Cont
Next Cont
MsgBox (total)

对我来说看起来更容易。

最新更新