static void Main(string[] args)
{
int i, n, sum = 0;
double avg;
Console.Write("Enter up to 10 numbers \n");
Console.Write("-------------------\n\n");
for (i = 1; i <= 10; i++)
{
Console.Write("Number {0}:", i);
n = Convert.ToInt32(Console.ReadLine());
sum += n;
if (i == 0)
{
break;
}
}
avg = sum / 10.0;
Console.Write("Sum: {0} \nAverage: {1}", sum, avg);
Console.Write("\n\nPress any key to exit..");
Console.ReadKey();
用户最多可以输入10个数字,这将返回每个数字之和,平均值和差。如果用户输入0,则代码将中断并计算用户先前输入的内容〜我的代码未正确中断,并且我迷失了我在做错的事情。 :(
答案 0 :(得分:4)
您正在验证if(i == 0),i是您的迭代器,并且从1开始,这种情况永远不会成立!
如果用户输入为0,则尝试if(n == 0)停止。
答案 1 :(得分:0)
您不想在i为0时中断,而是应该检查n是否为0。类似这样的事情:
static void Main(string[] args)
{
int i, n, sum = 0;
double avg;
Console.Write("Enter up to 10 numbers \n");
Console.Write("-------------------\n\n");
for (i = 1; i <= 10; i++)
{
Console.Write("Number {0}:", i);
n = Convert.ToInt32(Console.ReadLine());
sum += n;
// Changed the i to n
if (n == 0)
{
break;
}
}
avg = sum / 10.0;
Console.Write("Sum: {0} \nAverage: {1}", sum, avg);
Console.Write("\n\nPress any key to exit..");
Console.ReadKey();
}