26.3k views
4 votes
Given 4 integers, output their product and their average, using integer arithmetic.

Ex: If the input is:

8 10 5 4

the output is:

1600 6

Note: Integer division discards the fraction. Hence the average of 8 10 5 4 is output as 6, not 6.75.

Note: The test cases include four very large input values whose product results in overflow. You do not need to do anything special, but just observe that the output does not represent the correct product (in fact, four positive numbers yield a negative output; wow).

Also output the product and average, using floating-point arithmetic. Output each floating-point value with three digits after the decimal point, which can be achieved by executing cout << fixed << setprecision(3); once before all other cout statements.

User Okema
by
5.2k points

1 Answer

0 votes

Answer:

see explaination

Step-by-step explanation:

Part 1:

import java.util.Scanner;

public class LabProgram {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int num1;

int num2;

int num3;

int num4;

int avg=0, pro=1;

num1 = scnr.nextInt();

num2 = scnr.nextInt();

num3 = scnr.nextInt();

num4 = scnr.nextInt();

avg = (num1+num2+num3+num4)/4;

pro = num1*num2*num3*num4;

System.out.println(pro+" "+avg);

}

}

------------------------------------------------------------------

Part 2:

import java.util.Scanner;

public class LabProgram {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

int num1;

int num2;

int num3;

int num4;

double avg=0, pro=1; //using double to store floating point numbers.

num1 = scnr.nextInt();

num2 = scnr.nextInt();

num3 = scnr.nextInt();

num4 = scnr.nextInt();

avg = (num1+num2+num3+num4)/4.0; //if avg is declared as a float, then use 4.0f

pro = num1*num2*num3*num4;

System.out.println((int)pro+" "+(int)avg); //using type conversion only integer part

System.out.printf("%.3f %.3f\\",pro,avg);// \\ is for newline

}

}

User Clafouti
by
4.7k points