Printing Sum of Reciporicals of First 10 Positive integers [duplicate] - java

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 3 years ago.
I hav to write a simple program in bluej that computes and prints the sum of the reciprocals of the first 10 positive integers. My code is
public static void main (String[] args){
System.out.println(1/1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 +1/10);
}
It outputs the number 1. Can someone please explain why and tell me what the code should be?
My teacher said I shouldn’t use variables or anything.

Try 1.0/1.0 + 1.0/2.0 + etc.
The reason is the compiler interprets 1/2 as an integer divided by an integer which will return an integer (the floor of the true value). 1.0/2.0 is interpreted as a float/float which will return a float.
Google 'C integer arithmetic' for more.

Related

Java Multiple Two numbers issue with negative numbers [duplicate]

This question already has answers here:
Why I am getting -2147483648 and -1's multiplication, negative i.e. -2147483648, instead it should be +2147483648 [duplicate]
(1 answer)
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
How are integers internally represented at a bit level in Java?
(10 answers)
Why does the negative of Integer.MIN_VALUE give the same value? [duplicate]
(2 answers)
Closed 2 years ago.
I’m recently facing the below problem
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!
int i = -2147483648;
int j = i * -1;
System.out.println("j="+j);
}
}
Result : -2147483648
Online IDE with code :
https://paiza.io/projects/e/17lF_6-GltIcyubZv3QoFg?theme=twilight
But how it’s works as per the logic I need to get 2147483648 is a result right?
Then how I got this negative number ?
It’s because of integer range (Integer.MIN_VALUE)?
how to fix this issue?
The maximum postive value an int can hold is 2147483647 beyond which the value goes to the other end (i.e. it starts from the negative end). You can understand it from the following demo:
public class Main {
public static void main(String[] args) {
int i = -2147483648;
int j = i * -1;
System.out.println("j=" + j);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
// Some more examples for you to understand this concept better
System.out.println(Integer.MAX_VALUE + 2);
System.out.println(Integer.MAX_VALUE + 3);
}
}
Output:
j=-2147483648
2147483647
-2147483648
-2147483648
-2147483647
-2147483646
After -2147483648 is multipled with -1, it becomes 2147483648 but an int variable can not hold this much big positive value; so, it will start from the negative end (i.e. Integer.MIN_VALUE).
The number 2147483648 does not exists. The biggest value of an int is 2147483647, which is 1 smaller than your expected result. The multiplication causes an overflow, which 'rolls back' the number to the smallest negative value, and continues the calculation from there. (With other words: 2147483647+1=-2147483648 (smallest negative)) Since the result would only be 1 over the maximum value, there is no additional action required and the minimal int value is returned.
If you want to fix this issue, use 'long' instead of 'int' for your variables. You can also use more complex classes like BigDecimal, or write a custom multiplication function for byte arrays.
Note: no matter what numeric type you use, as long as the memory used for representing the number is finite you can run into similar issues. Although under normal circumstances it is unlikely, even for a 32-bit integer (int).

Java: How do I round a value that is between 0 and 1 to at least 3 decimal places? [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 2 years ago.
I'm trying to get a number when I divide 2 numbers together:
int wins = 3070;
int n = 10000;
double probability = wins/n;
System.out.println(probability);
All it prints is: 0.0
But I'm expecting it to print: 0.307
Atleast one of the values (numerator or denominator) should be type casted with double. Integer divided by integer would result integer. If one of them would be double then result would be upcasted to double. Try it! It should work!

Java Operator Precedence issue for a simple equation [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I am trying to implement a simple equation in Java but keep getting the wrong answer apparently due to operator precedence which I am unable to understand.
The equation is:
NewMean = ((N-1) / N) * OldMean + (Xn / N)
in a simple example:
N = 6 ; OldMean = 6 ; Xn = 16
So,
NewMean = 5/6 * 6 + 16/6 = 7.6667 (Correct answer)
but in code implementation on Java i get wrong answer (2.6665):
double NewMean = ((N-1)/N)*oldMean + (Xn/N);
If the N variable is type int, then ((N-1) / N) is computed using integer division and will round 5/6 down to 0. Change N to a floating-point type and you should get the correct answer.

Java casting (cast operator expressions) [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14

Modulo gives unexpected result

I have some problem with numerator, denumerator and modulo. 7 / 3 = 2.3333333333 gives me a modulo of 1!? Must be some wrong? I study a non-objective ground level course, so my code is simple and I have simplified the code below. (Some lines are in swedish)
Calling the method:
// Anropar metod och presenterar beräkning av ett bråktal utifrån täljare och nämnare
int numerator = 7;
int denumerator = 3;
System.out.println("Bråkberäkning med täljare " + numerator + " och nämnare " + denumerator + " ger " + fraction(numerator,denumerator));
And the method:
// Metod för beräkning av bråktal utifrån täljare och nämnare
public static String fraction(int numerator, int denumerator) {
// Beräkning
int resultat1 = numerator / denumerator;
int resultat2 = numerator % denumerator;
return Integer.toString(resultat1) + " rest " + Integer.toString(resultat2);
}
3 goes into 7 twice with 1 left over. The answer is supposed to be 1. That's what modulo means.
7 modulo 3 gives 1. Since 7 = 2*3 + 1.
7 % 3 = 1
Just as expected. If you want the .3333 you could take the modulo and devide it by your denominator to get 1 / 3 = 0.3333
Or do (7.0 / 3.0) % 1 = 0.3333
Ehm 7 % 3 = 1
What would you expect?
Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) can be thought of as the remainder, on division of a by n. For instance, the expression "5 mod 4" would evaluate to 1 because 5 divided by 4 leaves a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Notice that doing the division with a calculator won't show you the result referred to here by this operation, the quotient will be expressed as a decimal.) When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands.
More info : http://en.wikipedia.org/wiki/Modulo_operation
you didn't do a question!
And if your question is just:
"...gives me a modulo of 1!? Must be some wrong?"
No, it isn't, 7/3 = 2, and has a modulo of 1. Since (3 * 2) + 1 = 7.
You are using integer operands so you get an integer result. That's how the language works.
A modulo operator will give you the reminder of a division. Therefore, it is normal that you get the number 1 as a result.
Also, note that you are using integers... 7/3 != 2.3333333333.
One last thing, be careful with that code. A division by zero would make your program crash. ;)
% for ints does not give the decimal fraction but the remainder from the division. Here it is from 6 which is the highest multiplum of 2 lower than your number 7. 7-6 is 1.

Categories