我指的是如何对输入数字进行计数和求和,直到收到“结束”。
谢谢! 而且如何找出输入是c#中的数字或字母?class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
答案 0 :(得分:0)
我建议您使用普通的while循环,并添加验证以检查整数输入。
对于while循环,你想循环,直到输入不等于"结束":
root
对于验证,您可以使用while(inp != "end")
方法:
int.TryParse
以下是您的代码的修改示例:
int num = 0;
if (int.TryParse(inp, out num)) { }
答案 1 :(得分:0)
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
输入:
编号:
1
2
3
4
5
输出:
数:5
平均:3
这里唯一与你指定的不同的是任何无效或文本输入导致它完成,而不仅仅是输入单词&#34; end&#34;,尽管这显然也有效。