I cannot figure out how to get the correct answer when averaging numbers and trying to "float it"(?) I am trying to get the answer to be 6.750, but only keep getting 6.000.
Instructions:
2.31 LAB: Simple statistics
Part 1
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).
Submit the above for grading. Your program will fail the last test cases (which is expected), until you complete part 2 below.
Part 2
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 as follows:
System.out.printf("%.3f", yourValue);
Ex: If the input is 8 10 5 4, the output is:
1600 6
1600.000 6.750
Here is my code:
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 numAvg;
int numProd;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
numAvg = ((num1 + num2 + num3 + num4) / 4);
numProd = num1 * num2 * num3 * num4;
System.out.println(numProd + " " + numAvg);
System.out.printf("%.3f", ((double) numProd));
System.out.print(" ");
System.out.printf("%.3f", ((double) numAvg));
}
}
`
This lab requires you to write 2 different calculations for each part, one for integer numbers and one for double numbers. Using large input for part 1 will cause an overflow before you print the result because you defined the product and average as integers.
//Part 1
int product = num1*num2*num3*num4;
int average = (num1+num2+num3+num4)/4;
System.out.println(product+" "+average);
//Part 2
double prod = ((double)num1)*num2*num3*num4;
double ave = (double)(num1+num2+num3+num4)/4;
System.out.printf("%.3f", prod);
System.out.print(" ");
System.out.printf("%.3f", ave);
System.out.println();
Related
Part 1:
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).
Submit the above for grading. Your program will fail the last test cases (which is expected), until you complete part 2 below.
Part 2:
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 as follows:
System.out.printf("%.3f", yourValue);
Ex: If the input is 8, 10, 5, 4, the output is:
1600. 6
1600.000 6.750
Note that fractions aren't discarded, and that overflow does not occur for the test case with large values.
What I have,
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;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
double average_arith = (num1+num2+num3+num4)/4.0;
double product_arith = num1*num2*num3*num4;
int result1 = (int) average_arith;
int result2 = (int) product_arith;
System.out.printf("%d %d\n",result2,result1);
System.out.printf("%.3f %.3f\n",product_arith,average_arith);
}
}
So When I input example numbers everything checks out except overflow,
input: 100000 200000 300000 500000
Expected output:
-1679818752 275000
3000000000000000000000.000 275000.000
My output:
-1679818752 275000
-1679818752.000 275000.000
Any help please?
The result of multiplying two ints is an int. So here, you multiply the inputted numbers as ints (which causes them to overflow), and only then promote the result to a double. In order to get a non-overlowing result, you need to have at least one of the operands in each multiplication as a double. Since the * is left-associative, casting num1 to a double should do the trick:
double product_arith = ((double) num1) * num2 * num3 * num4;
-- Here ----------------^
I just did this lab too!
Mureinik has it right BUT I made a second product variable just for the overflow, and used the first one for the int. Does that make sense?
try using this code
int average;
average = (num1 * num2 * num3 * num4);
int product;
product = (num1 + num2 + num3 + num4) / 4;
double product2;
double average2;
average2 = ((double)num1 + num2 + num3 + num4 / 4.0);
product2 = ((double)num1 * num2 * num3 * num4);
Try this :)
Scanner scnr = new Scanner(System.in);
int num1;
int num2;
int num3;
int num4;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
int average;
average = (num1 * num2 * num3 * num4);
int product;
product = (num1 + num2 + num3 + num4) / 4;
double product2;
double average2;
average2 = ((double)num1 + num2 + num3 + num4);
product2 = ((double)num1 * num2 * num3 * num4);
System.out.printf("%d %d\n", average, product);
System.out.printf("%.3f %.3f\n", product2, average2 / 4.0 );
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 3 years ago.
I created a Java program that accepts three integers and would print the sum, product, the smallest and largest, and the average of these three integers.
import java.util.Scanner;
public class ThreeNums
{
public static void main (String[] args)
{
new ThreeNums();
}
public ThreeNums ()
{
int num1, num2, num3, sum, smallest, largest, exitPrompt = 0;
float average;
Scanner scan = new Scanner (System.in);
while (exitPrompt == 0)
{
System.out.printf ("\n\nPlease enter three integers.\n");
System.out.printf ("\t1st integer: ");
num1 = scan.nextInt();
System.out.printf ("\t2nd integer: ");
num2 = scan.nextInt();
System.out.printf ("\t3rd integer: ");
num3 = scan.nextInt();
System.out.printf ("\n");
sum = num1+num2+num3;
System.out.println ("Sum: " + sum);
System.out.printf ("Product: %d\n", num1*num2*num3);
if (num1<num2)
smallest = num1;
else
smallest = num2;
if (smallest<num3)
smallest = smallest;
else
smallest = num3;
if (num1>num2)
largest = num1;
else
largest = num2;
if (largest>num3)
largest = largest;
else
largest = num3;
System.out.printf ("Smallest integer: %d\n", smallest);
System.out.printf ("Largest integer: %d\n", largest);
average = sum/3;
System.out.printf ("Average: %.3f\n", average);
System.out.printf ("\nExit? 0 if NO, any other digit if YES\n");
exitPrompt = scan.nextInt();
}
System.out.printf ("\n\n");
}
}
Everything is okay except (I think) at lines 56-57:
average = sum/3;
System.out.printf ("Average: %.3f\n", average);
It is supposed to print the average of the three integers the user will input. For example, if the user inputs 5, 7, and 7, it is supposed to show that the average is 6.333:
Please enter three integers.
1st integer: 5
2nd integer: 7
3rd integer: 7
Sum: 19
Product: 245
Smallest integer: 5
Largest integer: 7
Average: 6.333
Exit? 0 if NO, any other digit if YES
But instead, for the average, it shows only 6.000.
.
.
.
Average: 6.000
.
.
If I input 78, 45, and 23, it only shows 48.000 instead of 48.667, and so on. What could be the problem with my code? Please help... Thanks!
Here: average = sum/3; both sum and 3 are ints, so the result is an int and then it's conferted into float. You can overcome this with this:
average = sum / 3.0;
I am making a program that accepts user input to subtract all the numbers desired by the user
I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count<=inputNum; Count++), so that the program loops for user input, based on the inputNum.
Unfortunately, the output is wrong. I can't understand how this would work properly.
I've tried switching the operator in difference by making difference =- toBeSubtracted; into difference -= toBeSubtracted;
For difference =- toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -5
For difference -= toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -15
Here is the code:
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
int toBeSubtracted = scan.nextInt();
difference =- toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
Ok this might help you out:
difference = 0
and than you have:
difference -= toBesubtracted
so what you are doing is:
difference = difference - toBeSubtracted
which in terms is
difference = 0 - 10
difference = -10 - 5
thus you get -15
and where you have
difference =- toBeSubtracted
it is the same as
difference = -1 * toBeSubtracted
thus you get -5
I suppose you want output of 5. Here is your code with one change
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = scan.nextInt(); // so read in the first number here.
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1;Count<inputNum; Count++) // go till from 1 to inputNum - 1 because you have already got one number above
{
int toBeSubtracted = scan.nextInt();
difference -= toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
You need to understand the operator shorthand notation. You should write -= for minus shorthand. The shorthand is equal to difference =difference - tobesubstracted. Since your initial value is 0 it becomes 0-10-5= -15.
Assign the first value as difference and then do the substraction of next values.
So something like:
difference = scanner.nextInt();
And then do the loop for rest of the values to minus from initial value.
The problem isn’t that your program is working incorrectly.
The problem is that the requirements are nonsense. You can have the difference between two numbers. The difference between 19 and 8 is 11. There is no such thing as the difference between 3 or more numbers. Therefore no program could ever produce that.
That said, Davis Herring is correct in the comment: there is no =- operator. You tried to use one in the line:
difference =- toBeSubtracted;
But the line is understood as just:
difference = -toBeSubtracted;
So your program just outputs the negative of the last entered number. I tried entering three numbers, 11, 3 and 5. The first time through the loop difference is set to -11. Next time this value is overwritten and -3 is set instead. In the final iteration the difference is set to -5, which “wins” and is output.
Instead I suggest that your program should always subtract 2 numbers, as you are also trying in your example. So the user needs not enter the number of numbers, but is just told to enter the two numbers. Then you also don’t need any loop. Just read the first number, read the second number, subtract the second from the first (or the first from the second, or the smaller from the larger, what you want) and print the result. I am leaving the coding to you to avoid spoiling it.
I did this
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
int currentNumber = 0; //current number from scanner
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
if(Count == 1)
{
//nothing to subtract if count is 1
currentNumber = scan.nextInt();
difference = currentNumber;
}
else {
currentNumber = scan.nextInt();
difference = difference - currentNumber;
}
}
System.out.println("The difference of those numbers is " + difference);
}
}
You started your difference at 0. So if you subtracted two numbers, 15 and 3, then you would get 0 - 15 - 3 = -18. I set the difference equal to the first number, 15 in the first loop. Then it should work correctly because you do 15 - 3 = 12.
I have a Printf formating question. I am to print only 10 numbers, before going to the next line and printing 10 more numbers and so on. with the end goal being like a table, with all the columns lining up and being aligned to the right. I am using a while statement as well. I have tried a few different things that I have found in my research, with no success. Would I use a different print statement for it other than Printf? Such as Print, or PrintLn? Also thought about using an If statement as well. Any help would be greatly appreciated! Thank you.
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
}
Using a MOD condition, You can ensure 10 output per line.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while (sqrt < n) {
sqrt = Math.pow(startNum, 2);
if(startNum != 0 && startNum % 10 == 0) {
System.out.println();
}
System.out.printf("%6.0f", sqrt);
startNum++;
}
}
}
Output -
Please enter a maximun integer value: 150
The number you entered was: 150
Squares less than 150 are: 0 1 4 9 16 25 36 49 64 81
121 144 169
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
if(startNum%10==0){
System.out.printf("/n");
}
}
Today i tried to make a simple program in Java that gives me the average of the numbers i entered.
The problem is that if i use int added (as shown below), i don't get the same answer as when i use double added.
Code:
public class Main {
public static void main(String[] args) {
int amount;
int number;
int added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.0
When i use double, i get the right answer:
public class Main {
public static void main(String[] args) {
int amount;
int number;
double added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result when i use double added instead of int added:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.5
Why does this happen and what should i do to avoid it?
To me it seems like added could be an int because i don't add up decimals but i add up whole numbers.
Thank you in advance.
In order for added/amount to return a non integer, either added or amount must be float or double or cast to either of them.
When both are int, an integer division takes place and the result is only converted to double after the division in order to be stored in your double average variable.
The result of a division in which both elements are integer, will be an integer. At least one of them needs to be a float or a double for the result of the division to be a floating point number.