小编Jaf*_*led的帖子

如何添加'n'个奇数?

我正在尝试编写一个计算前n个正奇数整数之和的程序.

我无法弄清楚如何将n合并到求和中.我已经有一个do/while循环来确保在赋值时得到正值.我知道我必须使用for循环,但我不确定我会怎么做.

Scanner input = new Scanner(System.in); // open input stream
    String cleanUpStr;                      // clean kbd buffer
    int n;                                  // number
    int sum;                                // sum of numbers
    int cntr;                               // counter for loop

    cleanUpStr = "nothing yet";
    n = 0;
    sum = 0;
    cntr = 0;

    //prompt user for the value of n
    // use a loop to ensure a positive output
    do
    {
        System.out.println("Enter the value of n");

        n = input.nextInt();
        cleanUpStr = input.nextLine();

        // print error if n …
Run Code Online (Sandbox Code Playgroud)

java loops

4
推荐指数
2
解决办法
175
查看次数

标签 统计

java ×1

loops ×1