close
  • 輸入繩子長度,每一天剪一半,計算需花多少天之後,繩子長度會小於3公尺
import java.util.Scanner;public class P5414 {	public static void main(String[] args) {		Scanner scn = new Scanner(System.in);		System.out.println("請輸入繩子的長度:");
		// a 繩子長度變數		int a = scn.nextInt();
		// count 天數變數,起始值0		int count = 0;		scn.close();
		// 只要i值大於0,持續執行		for (int i = 1; i > 0; i++) {
		// 如減去一半長度仍大於等於3公尺		// 再將a減去一半(意思就是除以2)		// 列印天數(count值)及減半後長度(除以2後之a值)		// 剪完一次,count值加1(天數加1天)		if (a >= 3) {		a = (a / 2);		count++;		System.out.println("第" + count + "天,長度變為 " + a + "公尺");
		// 若繩子短於3公尺,中斷for迴圈		} else			break;		}		System.out.println("總共需要 " + count + " 天");	}}
  • 執行結果(小數點不影響天數結果):
請輸入繩子的長度:3500第1天,長度變為 1750公尺第2天,長度變為 875公尺第3天,長度變為 437公尺第4天,長度變為 218公尺第5天,長度變為 109公尺第6天,長度變為 54公尺第7天,長度變為 27公尺第8天,長度變為 13公尺第9天,長度變為 6公尺第10天,長度變為 3公尺第11天,長度變為 1公尺總共需要 11 天
arrow
arrow

    ALVIN 發表在 痞客邦 留言(0) 人氣()