How do I use increment in calculations? - java

{int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);} //12
The compiler gives the num3 = 12, but how do I get that value? when I try to get that num3 value I got 6(by without using compiler). Both value of num2++ and ++num2 gives the same, but when I use following code it gives a different value. Why I got different values. what are the steps for get those num3 values (without using compiler?)
num3 = num2++ * num1 / num2 + num2; //11

Both increment operation num++ and ++num will result into num=num+1 there is only difference between the order of assignment and increment operations.
num++(post-increment) -> first num is used and then incremented
++num(pre-increment) -> first num is incremented and then used
You code prints 12 when I tested.
public static void main(String[] args) {
int num1 = 5;
int num2 = 6;
int num3;
num3 = ++num2 * num1 / num2 + num2;
System.out.println(num3);
}
I will suggest you to make use of brackets as it will increase readability as well.

If you do:
int num2 = 6;
System.out.println(num2++);
It will print 6, and then change num2 to 7. But if you do:
int num2 = 6;
System.out.println(++num2);
It will change num2 to 7 and then print 7. So:
num3 = ++num2 * num1 / num2 + num2;
num3 = 7 * 5/ 7 + 7
num3 = 35/7 + 7
num3 = 12

Related

3.16 LAB: Simple statistics Java

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 );

The total score always equals 0.0 no matter what input of num1, num2 or num3

What is wrong with this quote? It always outputs 0.0 instead of the total score result
import java.util.Scanner;
public class d {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1;
int num2;
int num3;
int percentnum1;
int percentnum2;
int percentnum3;
double totalscore;
System.out.print("Enter paper 1 score (out of 90): ");
num1 = input.nextInt();
System.out.print("Enter paper 2 score (out of 90): ");
num2 = input.nextInt();
System.out.print("Enter IA score (out of 20): ");
num3 = input.nextInt();
percentnum1 = (num1 / 90) * 100;
percentnum2 = (num2 / 90) * 100;
percentnum3 = (num3 / 20) * 80;
totalscore = (percentnum1 * 0.4) + (percentnum2 * 0.4) + (percentnum3 * 0.2);
System.out.println("The total score is " + totalscore);
}
}
Change int to double to avoid rounding down to 0.
If you like to use int types, you can multiply the number first. Hope it is helpful.
percentnum1 = num1 * 100 / 90;
percentnum2 = num2 * 90 / 100;
percentnum3 = num3 * 80 / 20;
seems like the code below is causing the problem:
percentnum1 = (num1 / 90) * 100;
percentnum2 = (num2 / 90) * 100;
percentnum3 = (num3 / 20) * 80;
if all of num1, num2 and num3 are values less than its denominators the result (totalscore) will be 0.0 because of integer division, even if some of the variables were 90/90 or 20/20 and others were less than it's denominators, you would again get the incorrect result and again due to integer division (though this time not necessarily 0.0).
The solution is to simply, use double types to keep the precision.
double num1;
double num2;
double num3
double percentnum1;
double percentnum2;
double percentnum3;
double totalscore;

Subtracting Random numbers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I'm making a game where the user must solve a simple subtraction but the result must be a positive whole number. I managed to do everything but for some reason the answer is sometimes negative and I'm not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class Subtraction {
public static void main(String[] args) {
Random r = new Random();
final int MAX = 10;
// get two random numbers between 1 and MAX
int num1 = r.nextInt(MAX) - 1;
int num2 = r.nextInt(MAX) - 1;
int total = (num1 - num2);
// display a question
System.out.printf("What is your answer to %d - %d = ?%n", num1, num2);
// read in the result
Scanner stdin = new Scanner(System.in);
int ans = stdin.nextInt();
stdin.nextLine();
// give an reply
if (ans == total) {
System.out.println("You are correct!");
} else {
System.out.println("Sorry, wrong answer!");
System.out.printf("The answer is %d + %d = %d%n", num1, num2, (num1 - num2));
}
}
}
Two possible solutions: Just change your total line with a condition to subtract the larger one from the smaller one (unless they're the same, in which case you'll get 0)
int total = (num1 > num2) ? (num1 - num2) : (num2 - num1);
Or just use the absolute value:
int total = java.lang.Math.abs(num1 - num2);
Change the printf as well:
System.out.printf("What is your answer to %d - %d = ?%n", (num1 > num2) ? num1 : num2, (num1 > num2) ? num2 : num1);
The conditionals are just making sure that the bigger number comes before the smaller number, or if they happen to be equal, that they are both listed.
Check out http://www.cafeaulait.org/course/week2/43.html for a more thorough explanation of the ? operator.
Generate your first value with room at the bottom for a second value to be subtracted, and the second one from a range bounded by the first:
int num1 = r.nextInt(MAX - 1) + 2; // produces values from 2 to MAX, inclusive
int num2 = r.nextInt(num1 - 1) + 1; // produces values from 1 to (num1 - 1), inclusive
The first number will always be strictly larger than the second, by construction, so the difference will always be a positive integer.
Well, with two random numbers in the same range, in random order, either cold be larger and the subtraction could be negative. Either fix how you get the numbers, or fix how they are ordered, or fix how you get their difference; any of these will do the job.
The code at the very heart of your program is wrong:
// get two random numbers between 1 and MAX
int num1 = r.nextInt(MAX) - 1;
int num2 = r.nextInt(MAX) - 1;
r.nextInt(MAX) returns a number between 0 (inclusive) and MAX (exclusive). Your code subtracts one from it, so you get a number in the range [−1, MAX−2].
Since you want it to be a simple subtraction where all numbers are in the range [1, MAX], you have to generate them that way. The general form of the subtraction is:
result = num1 − num2
This equation has the following constraints:
1 <= result <= MAX
1 <= num1 <= MAX
1 <= num2 <= MAX
result < MAX, since otherwise num2 would have to be 0
1 < num1, since otherwise the result would become negative
num2 < MAX, since otherwise result would have to be larger than MAX
This leaves the following allowed ranges:
1 <= result <= MAX − 1
2 <= num1 <= MAX
1 <= num2 <= MAX − 1
num2 <= num1 - 1
To generate these numbers, the code has to look like this:
int num1 = randomBetween(2, MAX);
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = randomBetween(1, maxNum2);
Now what is randomBetween? You have to define it:
randomBetween(min, max) ≡ r.nextInt(max + 1 - min) + min
Together, this is:
int num1 = r.nextInt(MAX + 1 - 2) + 2;
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = r.nextInt(maxNum2 + 1 - 1) + 1;
int result = num1 - num2;
assert 1 <= result && result <= MAX;
Since you know the result must be positive, I would start with the result
int total = r.nextInt(MAX) + 1;
int num2 = r.nextInt(MAX - total + 1);
int num1 = total + num2;
This way you can be sure that num1 - num2 will always be positive.
package optinalTest;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Subtraction {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
randomNumber();
}
}
private static void randomNumber() {
// get two random numbers between 1 and MAX
int num1 = ThreadLocalRandom.current().nextInt(10000, 9999998);
int num2 = ThreadLocalRandom.current().nextInt(num1 + 1, 9999999);
int total = (num2 - num1);
// display a question
System.out.printf("What is your answer to %d - %d = ?%n", num2, num1);
// read in the result
Scanner stdin = new Scanner(System.in);
int ans = stdin.nextInt();
stdin.nextLine();
// give an reply
if (ans == total) {
System.out.println("You are correct!");
} else {
System.out.println("Sorry, wrong answer!");
System.out.printf("The answer is %d - %d = %d%n", num2, num1, (num2 - num1));
}
}
}

Check if number is in range of Dynamically Changing Numbers?

Is there a way to determine if a number is within a range of two specific numbers, if those numbers are changing? For example:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if(num3 > num 1 && num3 < num2){
}
It would be rather easy to determine whether num3 is in between num1 and num2. However, lets say num1 and num2 change dynamically during the running of the program:
num2 becomes -30
All else remains the same. Now the same algorithm as before would no longer work. Is there an elegant way to check if a number is withing a range using dynamically changing max and min values?
You can try the following, i create 2 more variable iMin & iMax, and before checking num3 is in rank, we define max value and min value:
int num1 = -10;
int num2 = 100;
int num3 = 5;
if (num3 > Math.min(num1, num2) && num3 < Math.max(num1, num2)) {
}
That's kinda silly. If you have an algorithm in a function and you say you want num3 to be between num1 and num2, that's it. That rule shouldn't change, because num1 or num2 changed. The implementation should be generic and independent of the values.
If you need some verification prior to that, do it. I don't a see any other elegant way to do it.

explain this java code please

In this program if I enter 10 when it says enter a value what would be the output? num1 becomes 10, while num2 is 6, I don't understand what num1 = num1 mean? 10 = 10 + 2 = 12?
I think I understood it, it takes 10 from the user, num1 is then assigned the value of num1 + 2, which is 12. num2 then becomes num1, 12 then 12/6 = 2.
Output: 2
import java.util.*;
public class Calculate
{
public static void main (String[] args)
{
Scanner sc = new Scanner(system.in);
int num1, num2;
num2 = 6;
System.out.print("Enter value");
num1 = sc.nextInt();
num1 = num1 + 2;
num2 = num1 / num2;
System.out.println("result = " + num2);
}
}
It assigns the value of num1 + 2 back to num1.
So yes, if num1 = 10, the value 12 will be stored in num1.
Then that will be divided by 6, leaving 2.
Also, it never says num1 = num1, you can't isolate parts of a statement like that--the statement, an assignment, is num1 = num1 + 2.
What you have to understand is that num1 does not become a fixed number (eg 10) it remains a variable. And by definition a variable varies.
when you say x = 10 and then x = x+1, what really happens is something like this: y = x + 1 and then x = y
int num1, num2;
num2 = 6; // Now num2 has value 6
System.out.print(Enter value");
num1 = sc.nextInt(); // Now num1 has value 10, which you just entered
num1 = num1 +2; // num1 is being assigned the value 10 + 2, so num1 becomes 12
num2 = num1/num2; // Now num1 = 12 and num2 = 6; 12/6 = 2
System.out.println("result = "+num2);
You should get an output of 2; see above comments...
public class Calculate {
public static void main (String[] args) {
Scanner sc = new Scanner(system.in); // Whatever you read from System.in goes into the "sc" variable.
int num1, num2; // num1 = 0. num2 = 0.
num2 = 6; // num2 = 6.
System.out.print(Enter value");
num1 = sc.nextInt(); // Read in the next integer input and store it in num1.
num1 = num1 +2; // num1 gets 2 added to it and stored back in num1.
num2 = num1/num2; // num1 gets divided by num2 and the (integer) result is stored in num2.
System.out.println("result = "+num2); // Print out the result which is stored in num2.
}
}
In Java, the equal sign = is an assignment operator. It evaluates the expression on the right and assigns the resulting value to the variable on the left. So if num1 had the value 10 before the statement num1 = num1 + 2;, then after that statement it would have the value 12.
num1 = sc.nextInt();
num1 = num1 +2;
num2 = num1/num2;
In these statements, = is the assignment operator, not the equality operator. When you read it, don't say "equals", but rather "is assigned the value of":
num1 is assigned the value of sc.nextInt().
So, num1 is now 10.
num1 is assigned the value of num1 + 2
So, num1 is now 12
num2 is assigned the value of num1 / num2, or
num2 is assigned the value of 12 / 6
So, num2 is now 2.
It takes number input from user.
Adds 2 to the number that user entered.
Divides this value with 6 and add result to the num2 variable.
Prints "result = some number" to the user.
num1 = num1 +2;
means you are adding 2 to your num1. This can be represented as
num1 += 2; //which means the same as above
The outcome of your program will be determined by the integer division you are doing:
num2 = num1/num2;

Categories

Resources