简体   繁体   中英

How to write Java program that takes a number from a user and calculate sum and average of the numbers in between?

basic idea of the code

concept of the code to i just want only the averge i already done the sum.

import java.util.Scanner;
public class inbetweennumber {
    public static void main(String args []){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the 1st number");
        int num1 = input.nextInt();
        System.out.println("Enter the 2nd number");
        int num2 = input.nextInt();
        int sum = 0;
        double avg;

        for (int i = num1 + 1; i < num2; i++) {
            sum += i;
        }
        System.out.println("Sum: " + sum);
        avg = sum / num2;
        System.out.println("Average: " + avg);
    }
    
}

This not working for me. Example session:

Enter the 1st number
5
Enter the 2nd number
10
Sum: 30
Average: 3.0

The sum is correct: 6 + 7 + 8 + 9 = 30. The average should be 7.5 but comes out as 3.0.

Change avg = sum/num2; to avg = (double)sum/num2; , that will cast sum as a double , and dividing a double by an int will give you a double .

Right now, you are dividing an int by an int which returns an int , and then you are casting that int into a double , but by then it's too late.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM