學習隨筆——Java迴圈語句小例子
阿新 • • 發佈:2019-02-07
一、計算需要多長時間才能夠儲存一定數量的退休金
import java.util.Scanner;
public class Retirement {
public static void main(String[] args) {
//read inputs
Scanner in = new Scanner(System.in);
System.out.print("你退休需要多少錢?");
double goal = in.nextDouble();
System.out.print("你每年的報酬是多少錢?" );
double payment = in.nextDouble();
System.out.print("利率在%: ");
double interestRate = in.nextDouble();
double balance = 0;
int years = 0;
//在未達成目標時更新帳戶餘額
while(balance < goal){
//加上今年的付款和利息
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out.println("你可以在"+years+"年內退休.");
}
}
二、計算每年的餘額並由使用者決定是否滿足退休所用
import java.util.Scanner;
public class Retirement2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("你每年的報酬是多少錢?");
double payment = in.nextDouble();
System.out.print("利率在%: ");
double interestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input;
//在未達成目標時更新帳戶餘額
do{
////加上今年的付款和利息
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
//列印當前賬戶餘額
System.out.printf("在 %d年後,你的賬戶餘額是 %,.2f%n",year,balance);
//詢問是否準備退休並獲得收入
System.out.print("準備退休了嗎?(Y/N) ");
input = in.next();
}while(input.equals("N"));
}
}
三、計算數字抽獎中獎的概率
import java.util.Scanner;
public class LotteryOdds {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.print("你要猜幾個數字?");
int k = in.nextInt();
System.out.print("你能猜的最高數字是多少?");
int n = in.nextInt();
/*
* 計算二項式係數 n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
int lotterOdds = 1;
for(int i = 1;i<=k;i++){
lotterOdds = lotterOdds * (n-i+1) / i;
}
System.out.println("你的中獎概率為1/"+lotterOdds+".祝你好運!");
}
}