以下に、インターネットから検索して、C#でExcelのパーセントランク関数を計算する方法を示します。プログラムに合わせて少し変更しましたが、メインロジックは変更しませんでした。
プログラムはコンパイルされ、エラーなしで正常に実行されます(私が知っていることです)。ただし、コードをさらに確認すると、メインでは、を使用して関数を呼び出します
double result = percentRank( array, x);
どこ
xはint
配列であり、リスト(int)です。
これは、percentRankメソッドが取るように指定されているものとは異なるタイプですが、それでも正常に実行されます。私の質問はなぜですか?
private static double percentRank(List<int> array, double x)
{
// Calculate the PERCENTRANK(array, x)
//If X matches one of the values in the array, this function is
//equivalent to the Excel formula =(RANK(x)-1)/(N-1) where N is the number of data points.
//If X does not match one of the values, then the PERCENTRANK function interpolates.
// http://www.pcreview.co.uk/forums/algorithm-computing-excel-percentrank-t946312.html
array.Sort();
double result = 0;
bool foundX = false;
for (int index = 0; index < array.Count; index++)
{
if (array[index] == x)
{
result = ((double)index) / ((double)array.Count - 1);
foundX = true;
break;
}
}
// calculate value using linear interpolation
if (foundX == false)
{
double x1, x2, y1, y2;
x1 = x2 = x;
for (int i = 0; i < array.Count - 1; i++)
{
if (array[i] < x && x < array[i + 1])
{
x1 = array[i];
x2 = array[i + 1];
foundX = true;
break;
}
}
if (foundX == true)
{
y1 = percentRank(array, x1);
y2 = percentRank(array, x2);
result = (((x2 - x) * y1 + (x - x1) * y2)) / (x2 - x1);
}
else
{
// use the smallest or largest value in the set which ever is closer to valueX
if (array[0] > x)
{
result = 0;
}
else
{
result = 1;
}
}
}
return result;
}
編集:OK答えは暗黙の型変換です。無効にできますか?気づいていないバグが発生する可能性があるので、気に入らない。