C++ 函数--幽径初探索
1 #include <iostream> 2 using namespace std; 3 4 long double probability(unsigned numbers, unsigned picks); 5 6 int main() 7 { 8 cout << fixed; 9 int total, choices; 10 cout << "输入这场游戏共有多少选择的机会\n" 11 << "而玩家每次能选择几次?" << endl; 12 while((cin >> total >> choices) && choices <= total) 13 { 14 cout << "玩家参加了" << probability(total, choices) << "次活动才能赢得大奖\n" 15 << "输入下两个要测试的数字(按q退出):"; 16 } 17 cout << "bye!" << endl; 18 return 0; 19 } 20 21 //计算彩票中奖的概率。从numbers次机会中,取picks次 22 long double probability(unsigned numbers, unsigned picks) 23 { 24 long double result = 1.0; 25 unsigned n; 26 unsigned p; 27 28 for(n = numbers, p = picks; p > 0; n--, p--) 29 { 30 result = result * n / p; 31 } 32 return result; 33 }
鄙视'砖家'和'叫兽'