基本上我正在编写一种方法,我希望用for循环找到整数的总和。
输出应该是这样的:
Enter value of number 1: 23
Enter value of number 2: 23
Enter value of number 3: 23
The sum is: 69
用户可以选择要添加的多个号码。
我的代码目前看起来像这样:
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num = int.Parse(Console.ReadLine());
}
}
我该如何解决?
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no <whole numbers> " + index);
num += int.Parse(Console.ReadLine());
num = sum;
}
}
private void ShowResults()
{
Console.WriteLine("----------------------------------------------\n");
Console.WriteLine("The sum is \t{0}", sum);
似乎是解决方案+上面的类仍在使用但是是的。
非常感谢你们
答案 0 :(得分:1)
试试这个,
private static void SumNumbers()
{
int numOfInput = 3;
int index;
int num = 0;
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is:" + num.ToString());
Console.ReadLine(); // to keep console alive
}
希望有所帮助,
答案 1 :(得分:0)
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
Console.WriteLine("The sum so far is : "+num.ToString("N0")+". Enter another number to continue summation.");
}
Console.WriteLine("Maximum input received. Total is: "+num.ToString("N0")+".");
Console.ReadLine();
}
答案 2 :(得分:0)
这将根据您的需要运作:
int index;
int num = 0;
Console.WriteLine("Number of values to sum: ");
int numOfInput = int.Parse(Console.ReadLine());
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is: " + num);
将生成以下输出:
要求总和的数量:3
请给出1号的值 23个
请给出no 2的值 23个
请给出no 3的值 23个
总和是:69