0

尝试创建一个程序,该程序将观察一个数字并计算 1 和已观察到的数字之间的所有数字的数量。我被要求使用一个函数来做到这一点。当我运行程序时没有出现错误,它会观察数字并且之后什么都不做。有代码:

using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
     using System.Threading.Tasks;
 namespace ConsoleApplication2
 {
     class Program
     {
         static void Main(string[] args)
         {
            int i;
            int n=0;
            int a=0;
            Console.WriteLine("Enter a number: ");
            i = (Convert.ToInt32(Console.ReadLine()));
            AmountOfNumbers(ref i,ref n,ref a);
            Console.Write(a);
        }
         static void AmountOfNumbers (ref int i,ref int n,ref int a)
            {
            while (n < i)
            {
                a += n;
            }
            }
    }

}

任何帮助将不胜感激,谢谢。

4

4 回答 4

0

为了

while (n < i)
            {
                a += n;
            }

如果输入任何大于 0 的数字,则此条件将始终为真,因为您无法修改 n 的值。它应该是一个无限循环。

于 2013-06-21T15:58:07.630 回答
0
while (n < i)

n永远不会在循环中改变它的值,所以使用n = 0,这将导致一个无限循环,其中n(即0)被添加到a.

话虽如此,1和 任意整数n( n>1) 之间的数字数量是n - 1。无需循环任何东西。

于 2013-06-21T15:56:52.010 回答
0

您构建 while 循环的方式不正确。由于n = 0and 因此0总是小于输入的数字,因此该语句n < i将始终为真(我假设i > 0将输入)并且while循环将永远不会结束,它将是无限的。您需要递增n,以便在某个时候n > i循环退出。在此处查看有关 while 循环的更多信息:http: //www.dotnetperls.com/while

您想计算 1 和输入的数字之间有多少个数字,还是想将 1 和输入的数字之间的所有数字相加?

如果只是计数,你可以写:

static void AmountOfNumbers (ref int i,ref int n,ref int a)
{
   while (n < i)
   {
      a++;
      n++;
   }
}

如果你想要总和:

static void AmountOfNumbers (ref int i,ref int n,ref int a)
{
   while (n < i)
   {
      a += n;
      n++;
   }
}
于 2013-06-21T15:56:57.190 回答
0

函数通常是返回值的方法,因此您可能正在寻找更像

static int SumToN(int n)
{
    if (n > 0)
        // uses the formula for the sum of numners 1..n
        return n * (n + 1) / 2;
    else
        return 0;
}

static void Main(string[] args)
{
    int i = 0;
    int sum = 0;
    Console.Write("Enter a number: ");
    i = (Convert.ToInt32(Console.ReadLine()));
    sum = SumToN(i);
    Console.WriteLine(sum.ToString());
    Console.Read();
}

您可能还想检查输入值是否 <=65535,否则在计算总和时会发生溢出。

于 2013-06-21T17:44:33.837 回答