新手C#程序 请问错在哪了?

来源:百度知道 编辑:UC知道 时间:2024/07/02 19:26:56
using System;
class Sum
{public static void Main(string[] args)
{int n = Convert.ToInt32(args[0]);
int sum=0;
int i=1;
while (i <= n)
{sum = sum + i; i = i + 1; }
Console.WriteLine("n={0} sum={1}",n,sum); }
}
运行时候 提示:
未处理的异常:System.IndexOutOfRangeException:索引超出了数组界限

请问是哪错了 应该怎么改 555555555~~

你运行的时候没有输入参数,如果你生成的程序叫sum.exe, 那么你应该在CMD中用sum.exe 3514这样来运行它。


int n = Convert.ToInt32(args[0]);
中args大小为零,而你要访问他的第一个元素。
你也可以改成
using System;
class Sum
{public static void Main(string[] args)
{
if (args.Length == 0)
{
System.Console.WriteLine("错误:你的参数有误或者为空。");
return;
}
int n = Convert.ToInt32(args[0]);
int sum=0;
int i=1;
while (i <= n)
{sum = sum + i; i = i + 1; }
Console.WriteLine("n={0} sum={1}",n,sum); }
}

if (args.Length == 0)
{
System.Console.WriteLine("错误:你的参数有误或为空。");
return;
}
基本同意楼上