C-用户输入的数字的所有组合

时间:2019-01-19 11:29:29

标签: c

我有以下代码,但无法正常工作:

#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之间的数字,并且必须出现带有该用户数字的所有组合,而其余所有组合均不显示。

1 个答案:

答案 0 :(得分:0)

更多的话,您的程序中有一些奇怪的事情

  • 从未使用过读取的数字,因此无法根据它给出结果
  • 您可以修改 taken 以提供所有配对,但在为夫妇提供读取编号之前,您无需重置它,假设 taken 可以有效地用于这种情况下?
  • 在全球范围内为什么如此复杂?

您可以通过第二种方式用两种方法做到这一点:

#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)