我正在学习的书使用另一个库来读取输入,所以它不能帮助我....
我看不出我的错误在哪里。算法:
- 读取n的值
- 设置i的值为3
- 按照步骤操作
迭代
While i < 2*n
i+1
Write 1/(2*i+1) to the console.
我的代码:
import java.util.Scanner;
public class Aufgabe420 {
public static void main (String[] args) {
int i, n;
System.out.println("Please enter a number!");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("n ="+n);
System.out.println("The while-loop starts!");
i = 3;
while (i < 2*n){
i += 1;
System.out.println(1/(2*i+1));
}
System.out.println("now with for-loop");
for (i = 3; i < (2*n); i+=1) {
System.out.println(1/(2*i+1));
}
}
}
但是尝试一下,结果是: 请输入数字! 5
n=5 while 循环开始了! 0 0 0 0 0 0 0
现在有了for循环 0 0 0 0 0 0 0
这段代码有什么问题?感谢您的帮助。
最佳答案
1/(2*i+1)
对任何正的 i
都会产生 0,因为 1 < (2*i+1) 并且整数除法不能t 结果为分数。
改变
System.out.println(1/(2*i+1));
到
System.out.println(1.0/(2*i+1));
您想执行浮点除法,而不是整型除法。
关于Java:扫描器读取整数,但不在 while/for 循环中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071933/