我正在为我的计算机课程分配工作,我们的任务是编写一个分析数组“数字”的方法,并返回一个代表每个数字的数组,它作为前导数字出现的次数。 。
即 {100,200.1,9.3,10} 然后1%作为前导数字出现50%的时间,2发生25%的时间,9发生25%的时间,因此您生成的数组应包含: {0,.5,.25,0,0,0,0,0,0 .25}
我遇到了问题,建议我们编写一个名为helLeper的方法,例如countLeadingDigits,它返回每个数字的计数数组,然后才计算百分比。我不知道如何编写从用户那里获取未知数量的输入双精度的方法然后存储每个数字作为前导数字出现的次数..我已经编写了计算代码的一部分领先的数字。有什么提示吗?
答案 0 :(得分:1)
代码短而密集的解决方案:
public static void main(String[] args)
{
double[] inputs = { 100, 200.1, 9.3, 10 , -100 }; // your inputs
double sum = inputs.length;
int[] leadingDigitCounters = new int[10]; // counters for 0...9
// Here is how you increment respective leading-digit counters
for (double d : inputs)
{
int j = Integer.parseInt((d + "").replace("-", "").charAt(0) + "");
leadingDigitCounters[j]++;
}
// Printing out respective percentages
for (int i : leadingDigitCounters)
System.out.print((i / sum) + " ");
}
<强>输出:强>
0.0 0.6 0.2 0.0 0.0 0.0 0.0 0.0 0.0 0.2