基于整数值的整数减法和循环

Integer subtraction and looping based on integer values

我这里有两个问题。首先,我希望 x 将值更改为 x - y,如果新的 X 高于 0,我希望该过程自行重复。我已经制定了下面的代码,但我不确定两件事。

  1. 我什至可以做方程式 x = x - y 还是这会把一切都搞砸?我的意思是用数学术语来说这是不可能的,但如果我们将 X 作为 Hp,将 Y 作为伤害,我希望伤害加起来。我不希望它为每次减法创建一个 "damage HP" 整数,因为我什至不知道如果我将 Y 设置为随机,我必须创建多少 "Z = x - y" 样式方程。 我的猜测是我可以创建一个 Z 积分,它会在减法结束之前复制 X,然后让减法成为 X = Z - Y,但我不确定我将如何编写代码。

  2. 如果 X 高于 0,我希望它继续并自行循环,我不确定我的编码是否正确。

这是我的代码:

Module Module1
        Dim A As Integer
        Dim B As Integer
        Dim x As Integer
        Dim y As Integer
        Sub Main()

    End Sub

    Sub Maths()
        A = 5
        B = 4
        x = 3
        y = 1
        Subtraction()
        Console.WriteLine("You deal {0} damage to your enemy reducing it to {1} hp.", y, x)
            Do Until x <= 0

            Loop
    End Sub
    Private Sub Subtraction()
        If A > B Then x = x -y
            Return
    End Sub

End Module

我喜欢这个问题。这是我的想法:

  1. 是的,x = x - y 是完全有效的代码。这与我有一个名为 myRunOnSentence 的字符串变量没有什么不同,我想连接该变量中已有的字符串和另一个字符串,然后将结果存储回字符串变量中。像这样: myRunOnSentence = myRunOnSentence + "another string" 同样的概念,只是将数据类型更改为整数。 x = x + y。那以编程方式说:"take the value in x and the value in y, add them together, and store the result of that expression in x."

  2. 你确实在循环上犯了错误。您在循环体内没有任何代码。

  3. 您模块的 Main() 子模块中没有发生任何事情,因此当 运行 时该模块将不执行任何操作。您应该只从 Maths() 方法中获取代码并将其放入 Main() 子程序中。

  4. 在您的 Subtraction() 方法中,A > B 将始终计算为 True,因为 AB 是用值初始化的,并且然后就没变了。

您的代码应如下所示:

Module Module1
    Dim A As Integer = 5
    Dim B As Integer = 4
    Dim x As Integer = 3
    Dim y As Integer = 1

    Sub Main()
        Do Until x <= 0
            Subtraction()
            Console.WriteLine("You deal {0} damage to your enemy reducing it to {1} hp.", y, x)
        Loop
    End Sub

    Private Sub Subtraction()
        If A > B Then x = x - y 'Return statement wasn't needed.
    End Sub
End Module

如果这回答了您的问题,请不要忘记将其标记为答案。