Math.Max와 비슷하지만 int의 3 개 또는 params를 사용합니까?
감사
답변:
글쎄, 당신은 그것을 두 번 호출 할 수 있습니다.
int max3 = Math.Max(x, Math.Max(y, z));
이 작업을 많이 수행하는 경우 항상 자신 만의 도우미 메서드를 작성할 수 있습니다. 내 코드베이스에서이 작업을 한 번 볼 수 있으면 좋겠지 만 규칙적으로는 아닙니다.
(이것은 Andrew의 LINQ 기반 답변보다 더 효율적일 수 있지만 분명히 더 많은 요소가있을수록 LINQ 접근 방식이 더 매력적입니다.)
편집 : "양쪽 세계의 최고"접근 방식은 다음과 같은 방법으로 사용자 지정 메서드 집합을 갖는 것입니다.
public static class MoreMath
{
// This method only exists for consistency, so you can *always* call
// MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
// depending on your argument count.
public static int Max(int x, int y)
{
return Math.Max(x, y);
}
public static int Max(int x, int y, int z)
{
// Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
// Time it before micro-optimizing though!
return Math.Max(x, Math.Max(y, z));
}
public static int Max(int w, int x, int y, int z)
{
return Math.Max(w, Math.Max(x, Math.Max(y, z)));
}
public static int Max(params int[] values)
{
return Enumerable.Max(values);
}
}
이렇게하면 배열 생성의 오버 헤드없이 작성 MoreMath.Max(1, 2, 3)하거나 작성할 수 MoreMath.Max(1, 2, 3, 4)있지만 MoreMath.Max(1, 2, 3, 4, 5, 6)오버 헤드에 신경 쓰지 않아도 읽기 쉽고 일관된 코드를 작성할 수 있습니다.
개인적 으로 LINQ 접근 방식 의 명시 적 배열 생성 보다 더 읽기 쉽습니다.
MoreMath.Max(x, y, z)LINQ 접근 방식 인 IMO보다 훨씬 더 읽기 쉽습니다.
public static int Max(params int[] values) 않습니까?
Max(1, 2, 3)아무런 이유없이 배열이 생성됩니다. 상대적으로 적은 수의 매개 변수에 대해 몇 가지 오버로드를 제공하면 호출자의 가독성에 영향을주지 않고 더 효율적으로 만들 수 있습니다.
다음을 사용할 수 있습니다 Enumerable.Max.
new [] { 1, 2, 3 }.Max();
[]. 맵시 있는.
new int[] { 1,2,3 }. 따라서 그것은 내용에 의해 암시 적으로 결정되는 int 유형의 배열입니다.
Linq에는 Max 기능이 있습니다.
가있는 경우 IEnumerable<int>이를 직접 호출 할 수 있지만 별도의 매개 변수에서 필요한 경우 다음과 같은 함수를 만들 수 있습니다.
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
그런 다음 다음과 같이 호출 할 수 있습니다. max(1, 6, 2), 임의의 수의 매개 변수를 허용합니다.
Max가 아니라 max, 적은 매개 변수를 오버로드 : 그것이 정적하게, 당신은 너무 효율을 높일 수 있습니다.
주제에서 벗어 났지만 여기에 중간 가치에 대한 공식이 있습니다. 누군가가 그것을 찾는 경우를 대비하여
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
어떤 이유로 든 (예 : Space Engineers API) System.array에 Max에 대한 정의가 없거나 Enumerable에 대한 액세스 권한이없는 경우 Max of n 값에 대한 솔루션 은 다음과 같습니다.
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
priceValues []의 최대 요소 값은 maxPriceValues입니다.
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
이 함수는 정수 배열을 사용합니다. (배열 전송에 대한 @Jon Skeet의 불만을 완전히 이해합니다.)
아마도 약간 과잉 일 것입니다.
public static int GetMax(int[] array) // must be a array of ints
{
int current_greatest_value = array[0]; // initializes it
for (int i = 1; i <= array.Length; i++)
{
// compare current number against next number
if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
{
// array[i+1] exists
if (array[i] < array[i+1] || array[i] <= current_greatest_value)
{
// current val is less than next, and less than the current greatest val, so go to next iteration
continue;
}
} else
{
// array[i+1] doesn't exist, we are at the last element
if (array[i] > current_greatest_value)
{
// current iteration val is greater than current_greatest_value
current_greatest_value = array[i];
}
break; // next for loop i index will be invalid
}
// if it gets here, current val is greater than next, so for now assign that value to greatest_value
current_greatest_value = array[i];
}
return current_greatest_value;
}
그런 다음 함수를 호출하십시오.
int highest_val = GetMax (new[] { 1,6,2,72727275,2323});
// highest_val = 72727275