我正在尝试生成一个集合的幂集,并且编写了这段代码。问题是,当用户输入集合中两个相似的成员时,它无法正常工作。我能做些什么?
这是我的代码:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
char obtain(char *p,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<"enter member"<<(i+1)<<"\n";
cin>>*(p+i);
}
return *p;
}
void set_display(char *p,int n)
{
cout<<"{";
for(int i=0;i<n;i++)
{
cout<<*(p+i)<<",";
}
cout<<"}";
}
void powset(char *p,int n)
{
unsigned int m = (double)pow((double)2, n);
int i, j;
for(i = 0; i < m; i++)
{
cout<<"{";
for(j = 0; j < n; j++)
{
if(i& (1<<j))
cout<<*(p+j);
}
cout<<"}\n";
}
}
好吧,我无法在您丢失的地方调试您的代码。但自从你发布了你的问题后,我用纯代码编写了代码C
。也许您会发现它有帮助。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main(int argc, char* argv[]){
int N;
char y[20]={0};
int i,j;
y[0] = 'a';
y[1] = 'b';
y[2] = 'c';
N = 3;
int powerSet;
powerSet=pow(2,N);
for(i = 0; i<(powerSet);i++){
for(j=0;j<N;j++){
if((i & (1<<j))){
printf("%c ",y[j]);
}
}
printf("\n");
}
printf("\n");
return EXIT_SUCCESS;
}
及其工作原理:
:~$ gcc x.c -lm -Wall
:~$ ./a.out
a
b
a b
c
a c
b c
a b c
[ANSWER]
您的错误情况:当两个符号相同时。
y[0] = 'a';
y[1] = 'a';
y[2] = 'c';
:~$ ./a.out
a
a
a a
c
a c
a c
a a c
但根据集合论,这是错误的。因为在 Set 中我们不能两次拥有相同的元素(不止一次)。但输入也是错误的:(a, a, c)
不是一个集合。所以代码是可用的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)