C language daily practice
March 8, 2022
Article directory
Topic description
There are 12 balls in a pocket. It is known that 3 of them are red, 3 are white, and 6 are black. Now take 8 of them, how many possible color combinations are there?
problem analysis
This is a simple combination problem. It goes through all possible combinations and prints the combination of the total sum of 3 color balls to 8.
Code
#include <stdio.h>
int main()
{
int red = 0, white = 0, black = 0;
int cnt = 0;
for(red = 0; red <= 3; red++)
for(white = 0; white <=3; white++)
for(black = 0; black <= 6; black++)
if(red + white + black == 8)
{
printf("%-2d --- %d个红球,%d个黑球,%d个黑球\n",
++cnt, red, white, black);
}
printf("总共有%d种搭配.\n", cnt);
return 0;
}
operation result
online reference
Original link: http://c.biancheng.net/cpp/html/3316.html
This code saves a layer of loop.
#include<stdio.h>
int main()
{
int m, n, number=0;
printf(" 红球 白球 黑球\n");
printf("......................\n");
for( m=0; m<=3; m++ )
for( n=0; n<=3; n++ )
if(8-m-n<=6)
printf(" %2d: %d %d %d\n", ++number, m, n, 8-m-n);
return 0;
}