Question

I need to know how to translate this:

average

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;
}
Was it helpful?

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 using myInput.length
  • to iterate with a moving k index, you'll need a for loop. Check this out to know how to use for 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 write myInput[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:

averagefunction

Maybe you should try to:

  1. write a little method for p()
  2. write a for loop that performs a sum (the internet is full of these)
  3. adapt your for loop using p()
  4. divide the result of the for loop by n
  5. 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])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top