Java:Scanner读取整数,但不在while/for循环中使用它

3 java algorithm java.util.scanner

我正在学习的那本书使用另一个库来阅读输入,所以它无法帮助我....

我看不出我的错误在哪里.算法:

  1. 读取n的值
  2. 将i的值设置为3
  3. 按照步骤

重复

While i < 2*n

       i+1

       Write 1/(2*i+1) to the console.
Run Code Online (Sandbox Code Playgroud)

我的代码:

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));
    }


    }
}
Run Code Online (Sandbox Code Playgroud)

但尝试一下,结果是:请输入一个数字!五

n = 5 while循环开始!0 0 0 0 0 0 0

现在使用for-loop 0 0 0 0 0 0 0

这段代码出了什么问题?谢谢你的帮助.

Era*_*ran 6

1/(2*i+1)任何正数将导致0 i,因为1 <(2*i + 1)和int除法不能得到分数.

更改

System.out.println(1/(2*i+1));
Run Code Online (Sandbox Code Playgroud)

System.out.println(1.0/(2*i+1));
Run Code Online (Sandbox Code Playgroud)

你想要执行浮点除法,而不是int除法.

  • 好.有时这是最简单的事情,使得它变得困难. (3认同)