计算彩票赔率 - 关于代码的问题
Counting lottery odds - question about the code
我正在分析以下有关彩票赔率的代码,我有 2 个问题:
为什么要先将lotteryOdds的值设置为1(另外,这种情况在计算中是不是很常见?)
我知道计算赔率的公式(n*(n-1)...(n-k+1)/(1*2...*k),但是如果有人向我解释它是如何根据重复“for”循环工作的,我将不胜感激。
import java.util.Scanner;
public class LotteryOdds {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(" How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.println(" what is the highest numbers you can do draw? ");
int n = in.nextInt();
int lotteryOdds = 1;
for (int i = 1; i <= k; i++) {
lotteryOdds = lotteryOdds * (n - i + 1) / i;
System.out.println("Your odds are 1 in " + lotteryOdds + " . Good luck!");
}
}
}
lotteryOdds
变量需要为 1,因为如果你做 0 * 某事你将永远得到 0,所以程序总是 return 0。
至于循环,让我们更改值并通过循环:
第一次迭代:
lotteryOdds = 1 * (n - 1 + 1) / 1 = n / 1
第二次迭代:
lotteryOdds = n * ((n - 2 + 1) / 2) = (n / 1) * ((n - 1) / 2) = n *
((n - 1) / 2) = ((n * (n - 1)) / (1 * 2)
等
所以当你概括它时,你会得到:
(n * (n - 1)...(n - k + 1) / (1 * 2 ... * k) 就像上面的公式一样。
我正在分析以下有关彩票赔率的代码,我有 2 个问题:
为什么要先将lotteryOdds的值设置为1(另外,这种情况在计算中是不是很常见?)
我知道计算赔率的公式(n*(n-1)...(n-k+1)/(1*2...*k),但是如果有人向我解释它是如何根据重复“for”循环工作的,我将不胜感激。
import java.util.Scanner; public class LotteryOdds { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println(" How many numbers do you need to draw? "); int k = in.nextInt(); System.out.println(" what is the highest numbers you can do draw? "); int n = in.nextInt(); int lotteryOdds = 1; for (int i = 1; i <= k; i++) { lotteryOdds = lotteryOdds * (n - i + 1) / i; System.out.println("Your odds are 1 in " + lotteryOdds + " . Good luck!"); } }
}
lotteryOdds
变量需要为 1,因为如果你做 0 * 某事你将永远得到 0,所以程序总是 return 0。
至于循环,让我们更改值并通过循环:
第一次迭代:
lotteryOdds = 1 * (n - 1 + 1) / 1 = n / 1
第二次迭代:
lotteryOdds = n * ((n - 2 + 1) / 2) = (n / 1) * ((n - 1) / 2) = n * ((n - 1) / 2) = ((n * (n - 1)) / (1 * 2)
等 所以当你概括它时,你会得到: (n * (n - 1)...(n - k + 1) / (1 * 2 ... * k) 就像上面的公式一样。