[Feelings & Sharing] 用程序解决今天的问题
Tofloor
poster avatar
hanzn-zzx
deepin
2024-06-23 13:44
Author

main.cpp

#include 
#include 
#include "a.h"
using namespace std;


int main() {
	int redBalls = 5;
	int blueBalls = 3;
	int greenBalls = 2;
	int totalBalls = redBalls + blueBalls + greenBalls;
	int ballsToDraw = 5;

	long long totalCombinations = combination(totalBalls, ballsToDraw);

	long long combinationsWith3Red = combination(redBalls, 3) * combination(totalBalls - redBalls, ballsToDraw - 3);
	long long combinationsWith4Red = combination(redBalls, 4) * combination(totalBalls - redBalls, ballsToDraw - 4);
	long long combinationsWith5Red = combination(redBalls, 5);

	long long favorableCombinations = combinationsWith3Red + combinationsWith4Red + combinationsWith5Red;

	double Probability = static_cast(favorableCombinations) / totalCombinations;

	cout << Probability << endl;

	return 0;
}

a.h

long long combination(int n, int k) {
	if (k == 0 || k == n) return 1;
	if (k > n - k) k = n - k;
	long long result = 1;
	for (int i = 0; i < k; ++i) {
		result *= (n - i);
		result /= (i + 1);
	}
	return result;
}

本人初学C++,又是初中刚毕业,算法并不太会……

算是现学现用吧……(网上查了一堆才写出来的……)

Reply Favorite View the author
All Replies
hanzn-zzx
deepin
2024-06-23 13:47
#1

跑出来的结果,应该是对的吧……
图片.png

Reply View the author
兆兆嘟嘟嘟
deepin
2024-06-23 17:09
#2
hanzn-zzx

跑出来的结果,应该是对的吧……
图片.png

肯定对,你直接把这段代码私发给@deepin小助手

Reply View the author