我有以下代码,但无法正常工作:
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <string>
#define MAXN 100
const unsigned n=4;
const unsigned k=2;
int taken[MAXN];
void print(unsigned i)
{
unsigned l;
printf(" ( ");
for (l=0; l<=i-1; l++) printf("%u ", taken[l] + 1);
printf(")\n");
}
void variate(unsigned i)
{
unsigned j;
if (i>=k)
{
print(i);
return;
}
for (j=0;j<n;j++)
{
taken[i]=j;
variate(i+1);
}
}
void condition(unsigned number)
{
unsigned j;
if (number>=k)
{
print(number);
return;
}
for (j=0;j<n;j++)
{
taken[number]=j;
variate(number+1);
}
}
int main(void)
{
variate(0);
int number;
printf("Enter number from 1 to 4: \n", number);
scanf("%d", &number);
printf("All varians of the combinations with your number are: \n");
condition(0);
system ("pause");
return 0;
}
程序正在打印数字1、2、3和4的所有可能组合,并且可以正常工作。
但是void condition
工作不正常。在打印了这四个数字的所有可能组合之后,用户必须输入一个介于1和4之间的数字,并且必须出现带有该用户数字的所有组合,而其余所有组合均不显示。
答案 0 :(得分:0)
更多的话,您的程序中有一些奇怪的事情
您可以通过第二种方式用两种方法做到这一点:
#include <stdio.h>
#define MIN 1
#define MAX 4
int main()
{
/* print all couples */
for (unsigned i = MIN; i <= MAX; ++i) {
for (unsigned j = MIN; j <= MAX; ++j) {
printf("(%u %u)\n", i, j);
}
}
unsigned number;
printf("Enter number from %d to %d\n", MIN, MAX);
scanf("%u", &number);
/* first way following the same order as before */
puts("same order");
if ((number >= MIN) && (number <= MAX)) {
for (unsigned i = MIN; i <= MAX; ++i) {
for (unsigned j = MIN; j <= MAX; ++j) {
if ((i == number) || (j == number))
printf("(%u %u)\n", i, j);
}
}
}
/* an other way, faster but not in the same order */
puts("different order");
printf("(%u %u)\n", number, number);
for (unsigned i = MIN; i < number; ++i) {
printf("(%u %u)\n(%u %u)\n", number, i, i, number);
}
for (unsigned i = number + 1; i <= MAX; ++i) {
printf("(%u %u)\n(%u %u)\n", number, i, i, number);
}
return 0;
}
执行:
(1 1)
(1 2)
(1 3)
(1 4)
(2 1)
(2 2)
(2 3)
(2 4)
(3 1)
(3 2)
(3 3)
(3 4)
(4 1)
(4 2)
(4 3)
(4 4)
Enter number from 1 to 4
2
same order
(1 2)
(2 1)
(2 2)
(2 3)
(2 4)
(3 2)
(4 2)
different order
(2 2)
(2 1)
(1 2)
(2 3)
(3 2)
(2 4)
(4 2)