我正在努力解决我的一个课上提出的问题。提示符告诉我们让用户输入任意数字(可以是正数、负数或0),同时忽略非数字输入。然后我们需要计算并显示用户输入的所有数字的平均值。如果用户没有输入任何数字,我需要输出"您没有输入任何数字"。
我的主要问题是我不能正确地存储和添加用户给出的数字。我相当肯定,在while语句之前和之后的一切都是合理的。所以,我知道问题一定在while (enter!="Yes"||enter!="yes"||enter!="Y"||enter!="y")
,但我不确定问题是什么。由于我有用于平均值的变量,即用户给定数字的和,以及用于跟踪循环迭代的计数器,因此我很确定我的问题来自于我的代码顺序不正确。
Console.WriteLine("Please enter any numbers, then type Yes to continue.");
string enter = Console.ReadLine();
string msg = "";
decimal average;
int counter = 0;
decimal sum = 0;
bool res = decimal.TryParse(enter, out average);
while (enter!="Yes"||enter!="yes"||enter!="Y"||enter!="y")
{
sum = decimal.Parse(enter);
Console.WriteLine("Please enter any numbers, then type Yes to continue");
enter = Console.ReadLine();
sum += counter;
counter++;
}
average = sum / counter;
msg = (res) ? $"The sum of your numbers is {average}" : "You didn't enter any numbers";
Console.WriteLine(msg);
试试这个
static void Main()
{
int counter = 0;
decimal sum = 0;
bool exit=false;
do
{
Console.WriteLine("Please enter any number or type "done" to exit");
var enter = Console.ReadLine();
if (enter.Trim().ToLower() != "done")
{
var ok = decimal.TryParse(enter, out var num);
if(!ok) continue;
sum += num;
counter++;
} else exit=true;
} while (!exit);
var average = counter > 0 ? sum / counter:0;
var msg = average>0? $"The average of your numbers is {average}" : "You didn't enter any numbers";
Console.WriteLine(msg);
}
这里有一个可供您使用的替代方法。只是给你一些想法。
string enter = "";
string[] stop = new [] { "yes", "y" };
List<int> numbers = new List<int>();
while (!stop.Contains(enter.ToLowerInvariant()))
{
Console.WriteLine("Please enter any numbers, then type Yes to continue.");
enter = Console.ReadLine();
if (int.TryParse(enter, out int number))
{
numbers.Add(number);
}
}
if (numbers.Any())
{
Console.WriteLine($"The average of your numbers is {numbers.Average()}");
}
else
{
Console.WriteLine("You didn't enter any numbers");
}
试试这个......
string enter = "";
string msg = "";
decimal average;
int counter = 0;
decimal sum = 0;
decimal input;
while (enter!="Yes"&&enter!="yes"&&enter!="Y"&&enter!="y")
{
Console.WriteLine("Please enter any numbers, then type Yes to continue");
enter = Console.ReadLine();
bool res = decimal.TryParse(enter, out input);
if (res) {
sum += input;
counter++;
}
}
if (counter != 0)
{
average = sum / counter;
msg = $"The average of your numbers is {average}";
}
else {
msg = "You didn't enter any numbers";
}
Console.WriteLine(msg);
System.Threading.Thread.Sleep(5000);