Reputation: 10179
I know I could generate it using Math.log(2)
but I when I try to make up my own program to generate a natural log of 2 it continuously print 1. This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= n; i++) {
sum.add(new BigDecimal(1/n));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
I have tried to use float
, double
and int
and in the end used BigDecimal
but I still got 1 as the result I don't know why.
P.S It actually throws InputMismatchException
when big numbers are given i.e greater than 2000000000
or 2 Billion
.
Upvotes: 0
Views: 321
Reputation: 311308
n
is defined as an int
and 1
is an int
literal. When you divide two int
s you use integer arithmetic, which would return only the whole part of the fraction - in your case, 0
.
To rectify this, you should use double
s:
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d = scan.nextInt(); // Note we're assigning to a double
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= d; i++) {
sum.add(new BigDecimal(1.0/d));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
Upvotes: 1