从数组中查找最大值以及 C# 中的运行时错误是什么?
Finding the maximum from a array and what is runtime error in c#?
Given N numbers, find the one that is of the highest value and print it.
Input
The first line of the input will contain N (0 < N < 1000<N<100).
The following line will contain N integers, each between 11 and 10001000.
Output
Print the maximum.
我的回答是:
class program
{
static void Main(string[] args)
{
int N = Convert.ToInt32(Console.ReadLine());
int[] Numbers = new int[N];
int Le = 0;
for (int i = 0; i < N; i++)
{
Numbers[i] = Convert.ToInt32(Console.ReadLine());
}
//int m = 0;
for (int i = 0; i < N; i++)
{
Array.Sort(Numbers);
}
Console.WriteLine(Numbers[Numbers.Length-1]);
}
}
}
但它显示 运行时间错误。
谁能告诉我代码的正确答案以及什么是 运行 时间错误?
您只需要这样做:
int m = Numbers[0];
for (int i = 1; i < N; i++)
{
m = Numbers[i] > m ? Numbers[i] : m;
}
Console.WriteLine(m);
或者这个:
int m = Numbers[0];
for (int i = 1; i < N; i++)
{
int n = Numbers[i];
if (n > m)
m = n;
}
Console.WriteLine(m);
无需排序。
你的代码 运行 很好,但是对我来说没有错误。
Given N numbers, find the one that is of the highest value and print it.
Input
The first line of the input will contain N (0 < N < 1000<N<100).
The following line will contain N integers, each between 11 and 10001000.
Output
Print the maximum.
我的回答是:
class program
{
static void Main(string[] args)
{
int N = Convert.ToInt32(Console.ReadLine());
int[] Numbers = new int[N];
int Le = 0;
for (int i = 0; i < N; i++)
{
Numbers[i] = Convert.ToInt32(Console.ReadLine());
}
//int m = 0;
for (int i = 0; i < N; i++)
{
Array.Sort(Numbers);
}
Console.WriteLine(Numbers[Numbers.Length-1]);
}
}
}
但它显示 运行时间错误。
谁能告诉我代码的正确答案以及什么是 运行 时间错误?
您只需要这样做:
int m = Numbers[0];
for (int i = 1; i < N; i++)
{
m = Numbers[i] > m ? Numbers[i] : m;
}
Console.WriteLine(m);
或者这个:
int m = Numbers[0];
for (int i = 1; i < N; i++)
{
int n = Numbers[i];
if (n > m)
m = n;
}
Console.WriteLine(m);
无需排序。
你的代码 运行 很好,但是对我来说没有错误。