Can somebody please tell me how to translate this equation into a Java process? [closed]
Question
I need to know how to translate this:
into a Java process that looks like:
public static float computeAverage(float [] i){
//I have no idea what this is supposed to be.
}
or perhaps even
public static double computeAverage(double [] i){
//Still have no idea what this is meant to be.
}
If it's easier to answer with doubles, that's fine, but I really don't need that level of precision.
*Edit:*Okay, tell me if this looks right:
public static float computeAverage(float [] i){
float tally = 0f;
for(int x=0;x<i.length;x++){
tally = tally + pValue(i[x]);
}
return tally / i.length;
}
public static float pValue(float i){
return 2 - 1f/i;
}
Solution
I don't want to do your work right away, because it won't help you in the future. But I'll try to give you hints.
Java elements
The different elements that you might need are the following:
- the number
n
, which is the number of elements in your input array, can be accessed usingmyInput.length
- to iterate with a moving
k
index, you'll need afor
loop. Check this out to know how to usefor
loops. - you'll have to be careful that in Java, arrays are indexed starting at 0, not 1. So to access
Ck
, you'll actually writemyInput[k-1]
.
Break down your problem
What do you want to achieve? You're not just "translating this formula into Java code", but you're writing a method (a function) which, given an input array of Ci
, returns an average following the specified formula.
I think your assignment is to write the following function:
Maybe you should try to:
- write a little method for
p()
- write a
for
loop that performs a sum (the internet is full of these) - adapt your
for
loop usingp()
- divide the result of the
for
loop byn
- return the divided result
UPDATE: it's much easier to help you once you've tried something :)
Your code looks fine overall now. According to your formula I think you're adding the wrong value to the sum in your loop).
It should probably be: tally = tally + pValue(i[x])