algorithm - Java: Scanner reads integer, but doesn't use it in while/for loop -
my book i'm learning uses libary reading inputs can't me....
i can't see mistake is. algorithm:
- read value of n
- set value of 3
- follow steps
iterate
while < 2*n i+1 write 1/(2*i+1) console.
my code:
import java.util.scanner; public class aufgabe420 { public static void main (string[] args) { int i, n; system.out.println("please enter number!"); scanner sc = new scanner(system.in); n = sc.nextint(); system.out.println("n ="+n); system.out.println("the while-loop starts!"); = 3; while (i < 2*n){ += 1; system.out.println(1/(2*i+1)); } system.out.println("now for-loop"); (i = 3; < (2*n); i+=1) { system.out.println(1/(2*i+1)); } } }
but trying it, results in: please enter number! 5
n =5 while-loop starts! 0 0 0 0 0 0 0
now for-loop 0 0 0 0 0 0 0
what's wrong code? help.
1/(2*i+1)
result in 0 positive i
, since 1 < (2*i+1) , int division can't result in fractions.
change
system.out.println(1/(2*i+1));
to
system.out.println(1.0/(2*i+1));
you want perform floating point division, not int division.
Comments
Post a Comment