使用 vb.net 添加一个数字的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21896867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:50:15  来源:igfitidea点击:

adding the sum of a digit using vb.net

vb.net

提问by user3221761

i want to add the sum of a given digit i.e 1234 the sum is 10 this is my code

我想添加给定数字的总和,即 1234 总和是 10 这是我的代码

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim number As Integer
    Dim r As Integer
    Dim sum As Integer
    number = Val(TextBox1.Text)
    While (number <> 0)
        r = number Mod 10
        sum = sum + r
        number = number / 10
    End While
    Label3.Text = sum
End Sub

but when i input 123456 it gives me 24 instead of 21, whats wrong with my code?

但是当我输入 123456 时,它给了我 24 而不是 21,我的代码有什么问题?

采纳答案by BJ Myers

The operation number / 10uses regular division, which converts each number to a floating-point value, divides, and then coerces (rounds) the result back into an integer so it can be stored in numberagain. With the input 123456, after the first time through the loop, the new value of number is 12346instead of 12345as it should be.

该操作number / 10使用常规除法,将每个数字转换为浮点值、除法,然后将结果强制(四舍五入)回整数,以便number再次存储。对于 input 123456,在第一次循环后, number 的新值12346不是12345它应该的样子。

Instead, you need to use number \ 10, which performs integer division and does not round.

相反,您需要使用number \ 10,它执行整数除法并且不舍入。

More information on VB operators here.

有关 VB 运算符的更多信息,请访问此处

回答by peterG

This line number = number / 10should be number = number \ 10

这条线number = number / 10应该是 number = number \ 10

回答by mohamedagina

Sub Main() Console.Title = ("Sum of digits calculator") Dim x, sum As Double x = InputBox("Enter any number : ") sum = 0

Sub Main() Console.Title = ("数字总和计算器") Dim x, sum As Double x = InputBox("输入任意数字:") sum = 0

    While x > 0
        sum += x Mod 10
        x = (x / 10) - ((x Mod 10) / 10)

    End While
    Console.WriteLine("The sum of digits = " & sum)
    Console.ReadKey()

End Sub