在 VB.Net 中求平均数

发布于 2024-11-08 21:58:34 字数 204 浏览 0 评论 0原文

我正在尝试编写语法来在控制台应用程序中将十个用户输入的数字相加,然后将最终结果除以 10 以获得平均数。到目前为止,我能够允许用户正确输入数字,并且我已将程序设置为允许用户有时间读取结果,但是我在将数字相加的语法上略有困难。我知道这非常简单,但创建此代码的操作却让我无法理解。我已经尝试在网上寻找答案,但到目前为止,我唯一的结果过于复杂或完全错误。

任何和所有的帮助将不胜感激。

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 very 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你手 2024-11-15 21:58:34

有很多方法可以实现这一目标,但最简单的方法就是保留一个运行总数。您需要使用 double.Parse() 方法将字符串输入转换为双精度型。
runningTotal = runningTotal + double.Parse(Console.ReadLine())

最后输入后,只需将 runningTotal 除以 10 即可显示结果。

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.

柏林苍穹下 2024-11-15 21:58:34

具体如何取决于您用来存储数字的内容。 List(of Double) 对此很有用,因为它将存储任意数量的数字。然后可以使用一个简单的循环来添加它们。假设您的数字存储在一个名为“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()

它的作用是遍历数字,并将其中的每个数字添加到总数中。最后,它将总数除以数字数量(无论给你多少个)以获得平均值。请注意,您除以数字的数量即可得到平均值,不一定是 10。如果他们只给您 7 个数字,这个方法仍然有效。 :)

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. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文