gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:30:27 24 4
gpt4 key购买 nike

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

#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 条件 无法正常工作。打印完四个数字的所有可能组合后,用户必须输入 1 到 4 之间的数字,并且所有带有用户数字的组合都必须出现,其余组合均不出现。

最佳答案

更多评论已经完成,您的程序中有一些奇怪的事情

  • 读取的数字从未被使用过,因此无法根据它给出结果
  • 您修改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)

关于C - 用户输入数字的所有数字组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com