0

How can I do this in java? e=1+1÷1+1÷2+1÷3+...+1÷n

I must get n from uesr

20th Jan 2017, 3:50 PM
lordmak
lordmak - avatar
7 odpowiedzi
+ 4
double e = 1; for(int i = 1; i <= n; i++){ e += 1.0/i; }
20th Jan 2017, 3:53 PM
Robobrine
Robobrine - avatar
+ 2
Oops Sorry!!
20th Jan 2017, 4:01 PM
Megatron
Megatron - avatar
+ 2
@Megatron 1/i will always be 0 for i>1 as your division contains two integer and so the result will be an integer. You should make at least one of them float/double.
20th Jan 2017, 4:25 PM
Robobrine
Robobrine - avatar
+ 2
Scanner sc = new Scanner (System.in) ; int n = sc.nextInt(); First line creates object of scanner connected to your system input. Second uses this object to gather from keyboard and store a value to n variable.
20th Jan 2017, 4:50 PM
Maksym Zieliński
Maksym Zieliński - avatar
+ 1
@lordmark Posting the language would be helpful to others. There are many languages in sololearn.
20th Jan 2017, 3:55 PM
Megatron
Megatron - avatar
+ 1
C++(or the basic logic in every language is nearly same) cin>>n; float e=1; for(float i=1.0;i<=n;i++) e+=1/i;
20th Jan 2017, 3:56 PM
Megatron
Megatron - avatar
0
I should do it in java
20th Jan 2017, 3:58 PM
lordmak
lordmak - avatar