首页 文章

for循环递减2到0并总结在得到0之前生成的值

提问于
浏览
-3

我试图找到一种方法从用户输入的int倒计数,然后添加每个秒值,因为我倒数到0

例如 .

{用户输入10

计划倒计时8,6,4,2,0

然后加10 8 6 4 2 0 = 30

}

我怎么能使用嵌套的for循环来做到这一点

到目前为止,我只能接受用户输入,每次倒数2 . 我到0但没有办法增加每一个值 . 我的代码:

到目前为止,它只计为0

public class Week5b {static Scanner userVal = new Scanner(System.in);

public static void main(String[] args) {
  //printTable();
    reverseAddSkip();
public static void reverseAddSkip(){      

         System.out.println("Please enter an integer"); 


         for (int i = userVal.nextInt(); i >=0; i-=2){


         System.out.println(i) ;
        }/* this creates a loop where the variable i is equal to user input; 
            the condition for the loop to continue is whether the input is larger or   equal to 0; the update part of the loop takes 2 away each time, as if it were -- (which takes away one each time) */

}

我怎样才能用数学方法写出来?将i- = 2的总和加到i的原始值 . 你键入11,它计数9 7 5 3 1,然后加上11 9 7 5 3 1.并给你总和 .

不知道如何从用户值中减去每2个减2的数字 .

你输入50,它倒数2到0你把51倒计数2到0但我还没有发现总和所有那些在得到0之前生成的数字:/

2 回答

  • 0

    NoGlitching,

    您需要查看程序的 control flow - 也就是说,执行时所需的路径 .

    您还应该查看 using more variables .

    我会告诉你我会使用的伪代码,因为我认为能够自己编写代码对你很重要:

    • 创建一个名为OriginalInput的新整数 .

    • 创建一个名为RunningTotal的新整数 .

    • 将RunningTotal设置为0 .

    • 将用户的输入存储在OriginalInput中 .

    • 循环通过OriginalInput .

    • 打印当前的OriginalInput .

    • 将当前的OriginalInput添加到RunningTotal .

    • 循环结束时:

    • 打印RunningTotal .

    我希望这有帮助 .

  • 0

    编辑:

    // First you equalize j with i
    
             input =  userVal.nextInt();
             j = i; // Put the user input in j first. for instance 11.
    
         for (int i = input; i >=0; i-=2)
             {
               if (i >= 0) // If i is not below 0
                  {
                    j += i; // Add to j what i has now (everytime -2)
                    // put a system out print here to show what was added
                    // J starts as 11 and adds 9,7,5,3,1 then nothing. So it ends as 36.
                  }
    
    
              }
         // outside the For loop after it ends but INSIDE your method, you get the sum from the variable j!
    

相关问题