行き方: はint[] x
及びパーセンテージP(0から100)を考えるとは、少なくともパーセンテージx
のp
要素以下であるので、最小値の要素x
のy
を見つけますy
。ここでJavaの「フラクタイル」メソッド戻り間違った出力
Example 1:
x = {-3, -5, 2, 1}, p = 50
Method should return -3
Reason: 50% of the elements in x are less than or equal to -3: -5 and -3
Example 2:
x = {7, 9, 2, -10, -6}, p = 50
Method should return 2
Reason: 60 percent of the elements in x are less than or equal to 2: 2, -10 and -6
-6 would be wrong because only 40% of the elements are less than or equal
(100% of the elements are less than or equal to 9, but that isn't the smallest value)
Example 3:
x = {1,2,3,4,5,6,7,8,9,1,2,3,4,5,7,9,5,43,124,94}, p = 0
Method should return 1
Reason: Only 0% is needed, so in theory any number will do, but 1 is the smallest value
私はこれまでの方法のために書かれたものです:
public static int fractile(int[] x, int p)
{
int smallestInt = x[0];
for (int i = 0; i < x.length; i++) {
int testNum = x[i];
int percentage;
int count = 0;
for (int j = 0; j < x.length; j++) {
if (x[j] <= testNum)
count++;
}
percentage = (count/x.length) * 100;
if (testNum <= smallestInt && percentage >= p)
smallestInt = testNum;
}
return smallestInt;
}
しかし、私のサンプル数のための私の出力が間違って出てくる:
INPUT:
[6, 5, 4, 8, 3, 2]
40%
Method returns: 6
INPUT:
[7, 5, 6, 4, 3, 8, 7, 6, 9, 10]
20%
Method returns: 7
INPUT:
[3, 4, 2, 6, 7, 5, 4, 4, 3, 2]
60%
Method returns: 3
それはほとんどですあたかも最初のインデックスをつかんでいて、それの背後にある数字を見ないかのように私は理由を理解できません。
私は間違っていますか?ラインで
最大の問題があるかもしれないあなたの初期化ライン 'int型smallestInt = X [0];'。これは単に間違っています。 'int smallestInt = Integer.MAX_VALUE'のようなものに置き換えてください。 – Floris
Robert、最高指数または最高値を意味しますか? – Floris
以下のコメントと回答の一部に記載されているように、パーセント計算を修正する必要があります。 – Floris