打印1到该数字之间所有数字的总和.没有错误,它不工作
本文关键字:数字 有错误 工作 之间 打印 | 更新日期: 2023-09-27 18:19:19
尝试创建一个程序,该程序将观察一个数字并计算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;
}
}
}
}
任何帮助都将是感激的,谢谢。
while (n < i)
n
在循环中永远不会改变它的值,所以对于n = 0
,这将最终形成一个无限循环,其中n
(即0
)被添加到a
。
话虽如此,1
和任意整数n
(n>1
)之间的数字量是n - 1
。不需要循环任何东西
For
while (n < i)
{
a += n;
}
如果输入任何数字> 0,此条件将始终为真,因为您没有修改n的值。它应该是一个无限循环。
你构造while循环的方式是不正确的。由于n = 0
和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++;
}
}
函数通常是一个返回值的方法,所以您可能会寻找更像
的东西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,否则在计算总和时会发生溢出