2017-10-10 42 views
-6

我試圖將for循環的迭代總和加在一起。這是我迄今爲止所擁有的。在Java中一起添加迭代

import java.util.Scanner; 

public class Pennies 
{ 
    public static void main (String [] args) 
    { 
     double amount; //To hold the amount of pennies per day 
     double days; //To hold the days user saved. 
     double total; 

     System.out.println("I will display a table of salary if you're paid every day in pennies and it doubles every day."); 

     Scanner keyboard = new Scanner(System.in); 

     System.out.print("How many days do you wish to save for?"); 
     days = keyboard.nextDouble(); 

     //Display the table 
     System.out.print("Day \t Salary \n"); 
     for (amount = 1; amount <= days; amount++) 
     { 
      total = amount * .01 * amount; 
      System.out.println(amount + "\t \t $" + total); 
     } 
    } 
}        

任何幫助將不勝感激!

+2

究竟是什麼問題? –

+0

期望的輸出是什麼以及要改進的電流輸出是多少? – Zabuza

+0

期望的輸出將是一張表格,顯示每天加倍的薪水,然後在底部顯示所有迭代的總和。 –

回答

0

爲了不斷增加的工資的每一天,保持總的軌道每一天(我把它從你的陳述),您可以更改: -

total = amount * .01 * amount; 

total += amount * .01 * amount; // total = total + (amount*0.01*amount) 

其(當不單獨進行打印的每一天的信息)可以被簡化爲: -

total = amount * .01 * amount * days; 
0

I C剔除你的代碼,並注意到你的號碼已關閉。假設你希望第一天的工資是一分錢,並且每隔一天它就會翻一番,這就是我想出的結果。很難說這是否正是你想要的,因爲你實際上沒有提出問題,所以讓我知道這是你想要的。

public static void main(String[] args) { 
    System.out 
      .println("I will display a table of salary if you're paid every day in pennies and it doubles every day."); 

    Scanner keyboard = new Scanner(System.in); 

    System.out.print("How many days do you wish to save for?"); 
    double days = keyboard.nextDouble(); 

    // Display the table 
    System.out.print("Day \t Salary \n"); 
    double pay = 0.01; 
    double totalPay = 0.0; 
    for (int i = 1; i <= days; i++) { 
     System.out.println(i + "\t \t $" + pay); 
     totalPay += pay; 
     pay *= 2; 
    } 
    System.out.println("Total Pay \t $" + totalPay); 
    keyboard.close(); 
} 

你原本是在做total = amount*0.1*amount,它不會給你你想要的。你簡單地將它加倍,讓amount平平。

編輯:另請考慮將days更改爲int。我沒有看到任何理由爲什麼它應該是double

+0

我試圖將循環的迭代加在一起。 .4 + .6 + .8 +等,並提出最後的迭代總數。 –