【问题标题】:Problems with writing powerset code编写powerset代码的问题
【发布时间】:2013-02-23 19:30:20
【问题描述】:

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

#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# 有什么关系,所以我删除了 C# 标签。
  • 为什么在使用cout 时使用 C 语言标签,而该标签未在 C 或 C# 中定义?
  • 当你使用调试器时,错误出现在哪一行?
  • 另外,从不混合printfstd::cout。使用其中一种。
  • 请在您的问题中添加输入、预期输出和实际输出。

标签: c++ powerset


【解决方案1】:

好的,我无法调试您丢失的代码。但是自从你发布你的问题后,我用纯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 

但是根据集合论这是错误的。因为 在 Set 中我们不能有两次相同的元素(超过一个)。但也输入错误:(a, a, c) 不是一个集合。所以代码是可用的。

【讨论】:

  • 我写在C,因为你没有包含.h扩展的头文件。
  • 非常感谢,所以我的代码也可以正常工作,并且没有任何错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多