当用户输入“-1”时,如何将所有用户输入相加?在VB控制台内? [英] How do I add up all the users inputs when the user inputs "-1" inside VB console?

查看:125
本文介绍了当用户输入“-1”时,如何将所有用户输入相加?在VB控制台内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是让用户输入一个小于30的随机数,它会一直循环,直到用户键入-1,然后将所有输入加起来,然后是console.WriteLine(??)总。我还在尝试学习While循环,所以如果它是在一个while循环中完成的话会非常感激。





What I'm trying to do is get the user to input a random number less than 30 and it keeps looping until the user types "-1" then adds up all the inputs and it console.WriteLine(??) the total. I'm still trying to learn While Loops so it would be much appreciated if it was done in a while loop.


Module Module1

    Sub Main()
        Dim testing As Integer
        Dim WhileCounter As Integer = Console.ReadLine()

        While WhileCounter < 30
            Console.WriteLine("Enter a number: ")
            testing = Console.ReadLine()
            If testing = "-1" Then
                Console.WriteLine()
                Exit While
            End If
        End While

        Console.Read()
    End Sub

End Module





我的尝试:



我尝试了一些基本的东西,比如测试+1,但只加1到-1然后我尝试了WhileCounter + Testing。但我无法找到我必须做的事情。



What I have tried:

What I have try some basic things like testing +1 but that only adds 1 to -1 then I've tried WhileCounter + Testing. But I cant find out what I have to do.

推荐答案

随时添加它们:在循环外创建一个total变量,并将其初始化为零。

然后创建一个名为continue的布尔变量并将其设置为True。

使循环循环,直到continue不再为True。

在循环中,读取用户的输入,并使用TryParse将其转换为数字(如果TryParse返回False,则输入错误,请告诉他并忽略它)。

如果转换后的值为-1,则将continue设置为False。

否则,将转换后的值添加到总计

循环后,打印总计



这很简单,但因为这算作作业(你通过做而不是通过复制来学习)我会给你没有代码!

试一试,看看能走多远!
Add them up as you go: create a "total" variable outside the loop, and initialize it to zero.
Then create a Boolean variable called "continue" and set it to True.
Make your loop go round until "continue" is no longer True.
Inside the loop, read the input from the user, and convert it to a number using TryParse (if TryParse returns False, he entered it badly, so tell him off and ignore it).
If the converted value is -1, set "continue" to False.
Otherwise, add the converted value to the "Total"
After the loop, print "total"

It's pretty simple, but since this counts as homework (you learn by doing, not by copying) I'll give you no code!
Give it a try, see how far you can get!


这篇关于当用户输入“-1”时,如何将所有用户输入相加?在VB控制台内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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