用c语言写口袋中有红、黄、蓝、白、黑5种颜色的球若干个。每次从口袋中任意取出3个球,问得到3种不同颜色的球的可能取法,输出每种排列的情况(要求用字符串指针的方式完成编 程)。
时间: 2024-03-25 08:35:36 浏览: 51
好的,我来回答你的问题。
以下是用C语言编写口袋中5种颜色的球,每种颜色有若干个的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RED 0
#define YELLOW 1
#define BLUE 2
#define WHITE 3
#define BLACK 4
#define BALL_NUM 20
int balls[BALL_NUM];
void init_balls() {
int i;
for (i = 0; i < BALL_NUM; i++) {
int color = i % 5;
balls[i] = color;
}
srand(time(NULL));
}
int get_ball() {
int index = rand() % BALL_NUM;
int color = balls[index];
balls[index] = balls[BALL_NUM - 1];
BALL_NUM--;
return color;
}
```
接下来是题目要求的函数,使用字符串指针的方式输出每种排列的情况:
```c
void get_permutations() {
int i, j, k;
char *colors[5] = {"红色", "黄色", "蓝色", "白色", "黑色"};
char *str[3];
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
for (k = j + 1; k < 5; k++) {
int a = 0, b = 0, c = 0;
while (a == b || b == c || a == c) {
a = get_ball();
b = get_ball();
c = get_ball();
}
str[0] = colors[a];
str[1] = colors[b];
str[2] = colors[c];
printf("%s, %s, %s\n", str[0], str[1], str[2]);
}
}
}
}
```
在主函数中调用 `init_balls()` 函数初始化球的颜色,然后调用 `get_permutations()` 函数计算并输出结果:
```c
int main() {
init_balls();
get_permutations();
return 0;
}
```
这样就完成了题目要求的功能。