java homework. I need help with this code! We can use a loop to calculate and di
ID: 3595665 • Letter: J
Question
java homework. I need help with this code!
We can use a loop to calculate and display the value of the following series. The pattern seems pretty obvious and ideal for a simple loop. As you can see, We’re starting the pattern for the numerator from 1 to 9 and the denominator stars from 9 and goes down to 1 with steps of 2. Ask the user for the starting value and the ending value and compute the total. I need the value of the total displayed on the screen. So, if the first number is 1 and the last number is 9, we get the following series/pattern. 1/9 + 3/7 + 5/5 + … + 9/1 Make sure to watch for integer division and the problems with it. Hint: One loop with variables that handle the numerator and the denominator could do the job. Given the above series, the total should 12.87 be that you can test with your code. Format the total to display with 2 digits after the decimal point.
Explanation / Answer
SeriesTest.java
import java.util.Scanner;
public class SeriesTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the starting value: ");
int start = scan.nextInt();
System.out.println("Enter the ending value: ");
int end = scan.nextInt();
double total = 0;
for(int i=start, j=end;i<=end;i+=2,j-=2){
total = total + i/(double)j;
}
System.out.printf("Result: %.2f ",total);
}
}
Output:
Enter the starting value:
1
Enter the ending value:
9
Result: 12.87
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.