开发者

Averaging Numbers in VB.Net

I am trying to write the syntax to add up ten user-inputted numbers in a Console application, and then divide the final product by 10 in order to get the average number. So far I am able to allow the user to input the numbers properly, and I have the program set up to allow the user time to read the result, however I am slightly stuck on the syntax to add up the numbers overall. I know this is ve开发者_运维知识库ry simple, but the operation for creating this code is escaping me. I have tried finding the answer online already, but so far my only results have been overly-complex or just downright wrong.

Any and all help would be greatly appreciated.


There are lots of ways to acheive this, but the easiest is to just keep a running total. You'll need to cast the string input as a double using the double.Parse() method. runningTotal = runningTotal + double.Parse(Console.ReadLine())

After the last input, simply divide runningTotal by 10 to display the result.


Exactly how depends on what you're using to store the numbers. A List(of Double) would be good for this because it'll store an arbitrary amount of numbers. Then to add them you can use a simple loop. Assuming your numbers are stored in a List called "numbers":

Dim total as Double = 0;
Dim average as Double = 0;
For Each number as Double in numbers
    total += number
Next
average = total / numbers.Count()

What this does is goes through numbers, and for each number in it adds it to the total. At the end it divides the total by the count of numbers (however many you were given) to get the average. Note that you divide by the number of numbers to get the average, not necessarily 10. This one will still work if they only give you 7 numbers. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜