简体   繁体   English

计算彩票赔率 - 关于代码的问题

[英]Counting lottery odds - question about the code

I was analyzing the following code concerning Lottery Odds and I have 2 questions:我正在分析以下有关彩票赔率的代码,我有两个问题:

  • why do we need to set lotteryOdds' value to 1 first (also, is it a usual situation in calculations of this type?)为什么我们需要先将 lotteryOdds 的值设置为 1(另外,这是这种类型计算中的常见情况吗?)

  • I know the formula used for counting the odds (n*(n-1)...(n-k+1)/(1*2...*k), but if someone explained me how it works in accordance to repeating the "for" loop, I'd appreciate.我知道用于计算赔率的公式 (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!"); } }

    } }

The lotteryOdds variable needs to be 1, because if you do 0 * something you will always get 0, so the program will always return 0. As for the loop, lets change the values and go trough the loop: First iteration: lotteryOdds变量需要为 1,因为如果你做 0 * 某事,你总是会得到 0,所以程序将总是返回 0。至于循环,让我们更改值并遍历循环:第一次迭代:

lotteryOdds = 1 * (n - 1 + 1) / 1 = n / 1彩票赔率 = 1 * (n - 1 + 1) / 1 = n / 1

Second iteration:第二次迭代:

lotteryOdds = n * ((n - 2 + 1) / 2) = (n / 1) * ((n - 1) / 2) = n * ((n - 1) / 2) = ((n * (n - 1)) / (1 * 2)彩票赔率 = n * ((n - 2 + 1) / 2) = (n / 1) * ((n - 1) / 2) = n * ((n - 1) / 2) = ((n * (n) - 1)) / (1 * 2)

Etc. So when you generalize it you get: (n * (n - 1)...(n - k + 1) / (1 * 2 ... * k) just like in the formula above.等等。所以当你概括它时,你会得到: (n * (n - 1)...(n - k + 1) / (1 * 2 ... * k) 就像上面的公式一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM