【发布时间】:2018-10-07 13:48:13
【问题描述】:
我有一个简单的程序,告诉用户输入 n 个学生数量,为每个学生分配一个 x 个金额。最后,程序将 x 除以 n,这意味着总钱由学生平分。
问题是Console.Readline() 正在读取第二个输入值,如下所示。:
这意味着用户必须输入两次值,每次调用Console.Readline(),这显然是错误的!
代码:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = 0;
try
{
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt(Console.ReadLine());
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt(string s)
{
int numericValue = 0;
bool done = false;
while (!done)
{
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 100)
Console.WriteLine("The input must be between 0 and 1000!");
else
done = true;
}
return numericValue;
}
【问题讨论】:
-
仔细查看
checkInputTypeInt中的参数s。 -
您在主方法和 checkInputTypeInt 方法中都调用 Console.ReadLine()。你需要决定在哪里调用它,其中一个是多余的
-
哦,我调用了 Redline() 两次,谢谢!
标签: c# console-application readline