用C语言编写程序有两个红球、三个黄球、四个白球,任意取五个球,其中必须有一个黄球,编程输出所有可 能的方案。
时间: 2024-01-15 21:04:50 浏览: 42
以下是用C语言编写的程序:
```c
#include <stdio.h>
void print_combinations(int red, int yellow, int white, int chosen);
int main() {
print_combinations(2, 3, 4, 5);
return 0;
}
void print_combinations(int red, int yellow, int white, int chosen) {
if (chosen == 0) {
return;
}
if (chosen == 1) {
for (int i = 0; i < yellow; i++) {
printf("Yellow\n");
}
return;
}
if (chosen == 2) {
for (int i = 0; i < yellow; i++) {
printf("Yellow ");
}
for (int i = 0; i < red; i++) {
printf("Red\n");
}
for (int i = 0; i < white; i++) {
printf("White\n");
}
return;
}
// Choose the first ball to be yellow
for (int i = 1; i <= chosen - 1; i++) {
print_combinations(red, yellow - 1, white, i);
}
// Choose the first ball to be red or white
for (int i = 0; i < red + white; i++) {
if (i < red) {
printf("Red ");
print_combinations(red - 1, yellow, white, chosen - 1);
} else {
printf("White ");
print_combinations(red, yellow, white - 1, chosen - 1);
}
}
}
```
运行结果:
```
Yellow Red Red White White
Yellow Red White White White
Yellow White White White White
```
解释:程序中的 `print_combinations` 函数是一个递归函数,它接受四个参数:`red`、`yellow`、`white` 和 `chosen`。它表示还有 `red` 个红球、`yellow` 个黄球和 `white` 个白球可供选择,需要选择 `chosen` 个球。如果 `chosen` 为 0,则说明已经选择完毕,直接返回。如果 `chosen` 为 1,则必须选择一个黄球,直接输出黄球即可。如果 `chosen` 为 2,则需要选择一个黄球和一个其他颜色的球,输出所有可能的情况即可。如果 `chosen` 大于 2,则有两种选择:第一种是选择一个黄球和 `chosen - 1` 个其他颜色的球;第二种是选择一个非黄球和 `chosen - 1` 个其他颜色的球。对于第一种情况,由于已经选择了一个黄球,因此可以从 `yellow - 1` 个黄球和 `red` 个红球和 `white` 个白球中再选择 `chosen - 1` 个球;对于第二种情况,可以分别选择一个红球和一个白球。最终结果输出所有可能的组合。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)