编写电源集代码时出现问题

Problems with writing powerset code

本文关键字:问题 代码 电源      更新时间:2023-10-16

我正在尝试生成一个集的幂集,我写了这段代码。问题是,当用户输入两个相似的集合成员时,它无法正常工作。我能做什么?这是我的代码:

#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 

[答案]

错误情况:当两个符号相同时。

y[0] = 'a';
y[1] = 'a';
y[2] = 'c'; 
:~$ ./a.out 
a 
a 
a a 
c 
a c 
a c 
a a c 

但根据集合论,这是错误的。因为集合中的不能有两次相同的元素(多于一个)。但是INPUT也是错误的:(a, a, c)不是一个集合。所以代码是可用的。