我正在做我的计算机课程的作业,我们的任务是写一个方法来分析数组“数字”,并返回一个数组,表示每个数字,它作为前导数字出现的次数的比例……
例如{ 200.1,200.1,9.3,10}那么1作为前导数字出现的概率为50%,2出现的概率为25%,9出现的概率为25%,因此生成的数组应包含:{0,.5,.25,0,0,0,0,0,0,0,.25}
我在入门时遇到了问题,有人建议我们编写一个辅助方法,例如,countLeadingDigits,它返回每个数字的计数数组,然后才计算百分比。我不知道如何编写这样的方法:从用户那里获取未知数量的双精度输入,然后存储每个数字出现的次数作为前导数字。我已经编写了计算前导数字的代码部分。有什么建议吗?
发布于 2012-10-21 03:57:50
具有简短而密集的代码的解决方案:
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.2
https://stackoverflow.com/questions/12991981
复制相似问题