栗子 lotteryOdds: 这个在注释里面已经写的很明白了就是计算
代码:
import java.util.Scanner;
public class LotteryOdds {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//计算n*(n-1)*(n-2)*....(n-k+1)/k*(k-1)*...1
Scanner in = new Scanner(System.in);
System.out.println("How many numbers do ypu want to draw?");
int n = in.nextInt();
System.out.println("What is the Higher number you can draw?");
int k = in.nextInt();
int lotterodds = 1;
for(int i = 1; i <= k ; i++)
{
lotterodds = lotterodds*(n-i+1)/i;
}
System.out.println("your odds are 1 in "+ lotterodds +".Good Luck!");
}
}
下面一个栗子是也是计算退休金的,只是给出年率,每年存多少钱,然后最后获得多少钱。。。
代码:
import java.util.Scanner;
public class RetireTest2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//首先确定输入
Scanner in = new Scanner(System.in);
//呢一共要存多少钱养老
System.out.println("How much money do you want to contribute every year?");
double payment = in.nextDouble();
//年率是多少
System.out.println("Interest rate in %");
double intrestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input; //定义一个字符串
//下面主要是用do while 循环来解决问题 的
do
{
balance += payment ;
double interest = intrestRate*balance/100;
balance += interest;
year++;
//输出N年后的一共多少钱printf 和println 的区别
System.out.printf("After year %d, your balance is %.2f", year, balance);
System.out.println("Ready to Retire(Y/N)?");
input = in.next();//输入一个字符
}while(input.equals("N"));
}
}