vb.net 循环 - 添加数字 - Visual Basic

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13233256/
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 11:01:52  来源:igfitidea点击:

Loops - Adding Numbers - Visual Basic

vb.net

提问by Ds.109

So the program has to add all the numbers from "x" to "y".

所以程序必须把从“x”到“y”的所有数字相加。

But it also has to display all the numbers added :

但它也必须显示所有添加的数字:

i.e. 10 to 20 should display 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 165

即 10 到 20 应该显示 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 165

Here's what I have:

这是我所拥有的:

Dim firstnum As Integer = Val(TextBox1.Text)
    Dim secondnum As Integer = Val(TextBox2.Text)
    Dim sum As Integer = 0


    While firstnum <= secondnum

        sum = sum + firstnum
        firstnum = firstnum + 1

        Label3.Text = firstnum & "+"

    End While


    suum.Text = "  =  " & Val(sum)

采纳答案by Oded

With the following:

具有以下内容:

Label3.Text = firstnum & "+"

You are overwritingthe value in Label3every time you go through the loop. What you probably want to do is concatenatethe existing value with the next number.

你是覆盖在值Label3每次经过循环时间。你可能想要做的是串联的下一个数现有的值。

This should get you on your way:

这应该让你上路:

Label3.Text = Label3.Text & firstnum & " + "

回答by Tim Schmelter

Is Linq ok? Then you can use Enumerable.Rangeand Enumerable.Sum:

林克好吗?然后你可以使用Enumerable.RangeEnumerable.Sum

Dim startNum = Int32.Parse(TextBox1.Text)
Dim endNum = Int32.Parse(TextBox2.Text)
Dim numbers = Enumerable.Range(startNum, endNum - startNum + 1) 'inclusive, therefore + 1
Label3.Text = String.Join(" + ", numbers)
suum.Text = numbers.Sum()

回答by wxyz

your Label3.Text will only contain the last num and "+" at the end of the algorithm. You should replace

您的 Label3.Text 将只包含算法末尾的最后一个数字和“+”。你应该更换

Label3.Text = firstnum & "+" 

with

Label3.Text = Label3.Text & firstnum & "+ "