Java array with a for loop example

Read recently saw the array, and the use of the for loop.
In the evening when the phone brush to play a very fire while back piece:
girlfriend's father said: You gave me the first day 0.01 yuan, 0.02 yuan to me the next day, the third day to give me 0.04 yuan, and so on daily amount is twice the previous day, to the foot 30 days I'll marry your daughter.

See this issue, I subconsciously want to use an array to solve, but in the beginning knock discovered that arrays can not complete, there will be the first demo:

package my.list;

public class MoneyDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double a = 0.01;
		double allMoney = a;
		
		for (int i = 1; i < 31; i++) {
			System.out.println("第" + i + "天的金额为:" + a + "元");
			allMoney += a;
			a *= 2;
		}
		
		System.out.println("总金额为:" + allMoney);

	}

}

Results are as follows:
Here Insert Picture Description
Upon completion of this, put it in a personal sense if the array will be better, so there is less of this demo:

package my.list;

public class MoneyDemo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double[] moneyList = new double[30];
		double a = 0.01;
//		moneyList[0] = 0.01;
		double num = 0;
		
//		System.out.println("第1天的金额为:" + moneyList[0] + "元");
		
		for (int i = 0;i < 30; i++) {
			moneyList[i] =  a;
			System.out.println("第" + (i+1) + "天的金额为:" + moneyList[i] + "元");
			a *= 2;
			num += moneyList[i];
		}
		
//		for (int i = 0;i < 30; i++) {
//			num += moneyList[i];
//		}
//		
		System.out.println("总金额为:" + num);

	}

}

Modified, commented a few extra steps, but its operating results:
Here Insert Picture Description
above, is to think of the array as well as the for loop after reading the scripts. . .

Published 22 original articles · won praise 6 · views 4650

Guess you like

Origin blog.csdn.net/weixin_40615146/article/details/104306717