在列表中添加数字 [英] Add numbers in a list

查看:181
本文介绍了在列表中添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用visual studio,我选择了一个控制台应用程序



i有一个数字列表: 3,4,2

我想用任何迭代方法将它们加在一起

我该怎么做?



我尝试过:



i am using visual studio and i have selected a console application

i have a list of numbers: 3, 4, 2
and i want to add them together using any iterative method
how would i do this?

What I have tried:

Module Module1

    Sub Main()
        Dim numbers() As Integer = {4, 3, 2}
        Dim sum As Integer
        Dim finished As Boolean = False

        While finished = False
            Console.WriteLine(numbers)

            sum =
        End While
        Console.ReadLine()
    End Sub

End Module

推荐答案

除了 Richard Deeming 的解决方案#1之外[ ^ ] ...



这个:

In addition to solution #1 by Richard Deeming[^]...

This:
Dim numbers() As Integer = {4, 3, 2}



不是列表。 这是一个整数数组



这是列表(整数) [ ^ ]:


is NOT a list. It's an array of integers.

This is a List(Of Integer)[^]:

Dim myList As New List(OF Integer)()
myList.Add(4)
myList.Add(3)
myList.Add(2)





如何:创建项目列表| Microsoft Docs [ ^ ]



至少有几种方法可以实现这一目标:

1. For Each。 ..在...下一步 [ ^ ]

这样你就知道了现在



2。 For ... Next [ ^ ]



How to: Create a List of Items | Microsoft Docs[^]

There's at least few ways to achieve that:
1. For Each ... In ... Next[^]
This way you know now

2. For ... Next[^]

Dim numbers() As Integer = {4, 3, 2}
Dim sum As Integer = 0

For i As Integer = 0 To numbers.Length -1
	sum += numbers(i)
Next

Console.WriteLine("Sum: {0}", sum)





3. 虽然......循环直到或做......当...... [ ^ ]





3. While ... Loop Until or Do ... While ...[^]

While i < numbers.Length
	sum += numbers(i)
	i +=1
End While







Do 
	sum += numbers(i)
	i +=1
Loop While i < numbers.Length







有关循环的更多详情,请参阅:循环结构(Visual Basic)| Microsoft Docs [ ^ ]



实现这一目标的另一种方法是使用Linq:




For further details about loops, please reaad this: Loop Structures (Visual Basic) | Microsoft Docs[^]

Another way to achieve that is to use Linq:

Dim sum = numbers.Sum(Function(x) x)





请参阅:

LINQ:.NET语言集成查询 [ ^ ]

Visual Basic中的LINQ简介| Microsoft Docs [ ^ ]



祝你好运!



See:
LINQ: .NET Language Integrated Query[^]
Introduction to LINQ in Visual Basic | Microsoft Docs[^]

Good luck!


Dim numbers() As Integer = {4, 3, 2}

Dim sum As Integer = 0
For Each number As Integer In numbers
    sum += number
Next

Console.WriteLine(sum)



For Each ... Next Statement( Visual Basic)| Microsoft Docs [ ^ ]


这篇关于在列表中添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆