Your method should accept a real number as a parameter representing a limit, and should add and print terms of the sequence until the sum of terms meets or exceeds that limit. For example, if your method is passed 2.0, print terms until the sum of those terms is at >= 2.0. You should round your answer to 3 digits past the decimal point.
The following is the output from the call sequenceSum(2.0);
1 + 1/2 + 1/3 + 1/4 = 2.083If your method is passed a value less than 1.0, no output should be produced. You must match the output format shown exactly; note the spaces and pluses separating neighboring terms.
I'm wondering if there's anything I can do for the edge case of n = 1
? It kinda just seems like it's hanging out at the end, and it looks a bit strange to me. Also, looking at the types for each value, I'm wondering if I need to think more about the data types I chose to use, in terms of should I use a double
for this, or an int
?.
I'd use methods to break out the functionality of my code, but the prompt only allows me to submit one method for this type of problem. Any feedback is appreciated!
public static void sequenceSum(double n){
if(n > 1.0){
int denominator = 1;
double accumulator = 0;
System.out.print("1");
while(accumulator < n) {
accumulator += ( 1.0 / denominator);
if(denominator > 1.0){
System.out.print(" + " + 1 + "/" + denominator);
}
denominator++;
}
System.out.printf(" = %1.3f", accumulator);
} else if(n == 1.0){
System.out.print("1 = 1.000");
}
}