我必须用 C 代码生成查找表的所有可能输入。我确信它必须递归完成,但我找不到任何方法。你有什么建议吗?谢谢
int main()
{
int i,j,k;
int M,N;
int comb;
FILE *fp;
printf("Insert M and N values \n");
scanf("%d", &M);
scanf("%d", &N);
comb = (int) pow(2.0,M);
int A[comb][M];
int B[comb][N];
time_t t;
srand((unsigned) time(&t));
fp = fopen("lut.txt","w");
fprintf(fp, "INPUTPINS - %d\n", M);
fprintf(fp, "OUTPUTPINS - %d\n", N);
for (i=0; i< comb; i++)
{
for(j= 0; j<M; j++)
{
fprintf(fp,"%d", A[i][j]);
}
fprintf(fp, " - ");
for (k=0; k<N; k++)
{
B[i][k] = rand()%2;
fprintf(fp, "%d", B[i][k]);
}
fprintf(fp,"\n");
}
fclose(fp);
return 0;
}
我需要生成矩阵 A 的值,其中包含所有可能的 2^n 输入,而输出是随机的。
最佳答案
我不明白为什么你需要数组或递归来查找权限。权限是 0 到 2^M - 1 范围内的每个数字。您所需要的只是一个以二进制输出的函数。对 scanf()
和 fopen()
进行一些错误检查会更好。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void pbinary(FILE *fp, int val, int bits)
{
int mask = 1 << (bits-1);
while (bits-- > 0) {
fprintf (fp, "%d", (val & mask) != 0);
mask >>= 1;
}
}
int main()
{
int i, M, N, comb;
FILE *fp;
printf("Insert M and N values \n");
scanf("%d", &M);
scanf("%d", &N);
comb = 1 << M;
srand((unsigned)time(NULL));
fp = fopen("lut.txt","w");
fprintf(fp, "INPUTPINS - %d\n", M);
fprintf(fp, "OUTPUTPINS - %d\n", N);
for (i=0; i< comb; i++)
{
pbinary (fp, i, M);
fprintf(fp, " - ");
pbinary (fp, rand(), N);
fprintf(fp,"\n");
}
fclose(fp);
return 0;
}
程序输入
Insert M and N values
3
4
文件输出
INPUTPINS - 3
OUTPUTPINS - 4
000 - 1001
001 - 0101
010 - 0110
011 - 0100
100 - 1001
101 - 0011
110 - 0111
111 - 1111
关于c - 生成查找表的所有可能的二进制输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693742/