2014-11-08 29 views
-3

我想找到一種方法來從用戶輸入的int倒數,然後添加每個第二個值,因爲我計數降至0for循環遞減2到0,並總結得到0之前生成的值

例如。

{用戶輸入10

程序遞減計數8,6,4,2,0

然後加入10 + 8 + 6 + 4 + 2 + 0 = 30

}

我怎樣才能做到這一點使用嵌套for循環

到目前爲止我只能夠採取用戶輸入,並每次倒數2。我達到0,但無法添加每秒的值。 我的代碼:

到目前爲止,它只是計數爲0

公共類Week5b { 靜態掃描儀userVal =新的掃描儀(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 之前生成的所有然後是數字:/

+1

你如何申報Java中的int變量?你如何在Java中添加兩個數字? – 2014-11-08 15:47:31

回答

0

NoGlitching,

你需要看看你的程序的控制流 - 這是說,它需要在執行的路徑。

你還應該看看使用更多變量

我會給你我會用僞代碼,因爲我覺得你是能夠自己編寫的代碼是很重要的:

  • 建立一個叫做OriginalInput新的整數。
  • 創建一個名爲RunningTotal的新整數。
  • 將RunningTotal設置爲0.
  • 將用戶的輸入存儲在OriginalInput中。
  • 循環通過OriginalInput。
    • 打印當前OriginalInput。
    • 將當前的OriginalInput添加到RunningTotal。
  • 當循環結束:
    • 打印RunningTotal。

我希望這會有所幫助。

+0

欣賞您的幫助bro,但我很難過,因爲我必須使用嵌套for循環來做到這一點。基本上,我認爲有一個數學解決方案。 i- = 2最終爲0.所以即使i- = 2 + i 8- = 2 + 8 = 14?這將是加6,這是前2個數倒數2,但我不能表達它怎麼做在紙上:( – NoGlitching 2014-11-08 16:00:39

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! 
+0

試過,但似乎只是從我輸入的數字倒數到0,我想添加所有的數字,我必須計數,以達到0,所以如果有人輸入12,程序應該輸出42 – NoGlitching 2014-11-08 19:50:02

+0

這是我編輯的同一評論的解決方案,希望它有幫助,接受它,如果案件解決。否則,請留下一個答覆 – 2014-11-08 23:50:46

+0

那麼,它是有道理的,但不起作用。事情是,我只需要找到記住數字行的方法,或者將每個值存儲在循環中倒數到一個變量中。知道該怎麼做,所以想象一下,i = 2 ....所以每次2被帶走,該值就被存儲在一個變量中,顯然,第一次它不會遞減或遞增,所以初始值價值也將被存儲在同一個變量給出正確的結果,並仍然在勾選框我在打印答案之前,t倒數2到0 – NoGlitching 2014-11-10 16:55:48