您需要在未达到 100 的总和时进行循环,因此条件为inputList.Sum() < 100
.
如果总和和新数字大于 100,则告诉用户。如果不是这种情况,那么您可以将它们加在一起。
此外,您应该向用户查询int
,除非您确实需要一个十进制数(如果是这种情况,您需要使用 epsilon 检查相等性,小数和“完全相等”不能很好地结合在一起)。
这给出了以下内容:
static void Main(string[] args)
{
List<int> inputList = new List<int>();
do
{
Console.Write("Enter your number: ");
int numberToAdd = Convert.ToInt32(Console.ReadLine());
if (numberToAdd + inputList.Sum() > 100)
{
Console.WriteLine("Number will not be added, {0} is greater than 100", numberToAdd + inputList.Sum());
}
else
{
inputList.Add(numberToAdd);
}
} while (inputList.Sum() < 100);
double sum = inputList.Sum();
Console.WriteLine("The sum is " + sum);
double avg = sum / inputList.Count;
Console.WriteLine("The average is " + avg);
Console.ReadLine();
}
稍微清理一下:
static void Main(string[] args)
{
List<int> inputList = AskUserForInput();
PrintSum(inputList);
PrintAverage(inputList);
Console.ReadLine();
}
private static List<int> AskUserForInput()
{
List<int> inputList = new List<int>();
do
{
Console.Write("Enter your number: ");
int numberToAdd = Convert.ToInt32(Console.ReadLine());
if (IsGreaterThan100(numberToAdd, inputList))
{
Console.WriteLine("Number will not be added, {0} is greater than 100", numberToAdd + inputList.Sum());
}
else
{
inputList.Add(numberToAdd);
}
} while (IsSumLowerThan100(inputList));
return inputList;
}
private static bool IsGreaterThan100(int numberToAdd, List<int> inputList)
{
return numberToAdd + inputList.Sum() > 100;
}
private static bool IsSumLowerThan100(List<int> inputList)
{
return inputList.Sum() < 100;
}
private static void PrintAverage(List<int> inputList)
{
double avg = inputList.Sum() / inputList.Count;
Console.WriteLine("The average is " + avg);
}
private static void PrintSum(List<int> inputList)
{
double sum = inputList.Sum();
Console.WriteLine("The sum is " + sum);
}
}