用Java生成真值表

Dav*_*eng 8 java truthtable

我正在尝试打印一些真值表作为学校作业的一部分.如何在Java中生成动态大小的真值表?

这样printTruthTable(1)打印:

0
1
Run Code Online (Sandbox Code Playgroud)

printTruthTable(3) 打印:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Run Code Online (Sandbox Code Playgroud)

等等.我一直在尝试使用递归来实现它,但我无法做到正确.

sva*_*rog 15

这是我对你的问题的看法,所有写得很好而且很小,只是复制/粘贴

注意我是如何使用modulo2(%符号)从循环索引中获取0和1的

public class TruthTable {
    private static void printTruthTable(int n) {
        int rows = (int) Math.pow(2,n);

        for (int i=0; i<rows; i++) {
            for (int j=n-1; j>=0; j--) {
                System.out.print((i/(int) Math.pow(2, j))%2 + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        printTruthTable(3); //enter any natural int
    }
}
Run Code Online (Sandbox Code Playgroud)


das*_*ght 11

这不是真值表 - 相反,它是二进制数表.您可以使用Java的Integer.toBinaryString方法生成您需要的零和一个; 插入空格应该是微不足道的.

int n = 3;
for (int i = 0 ; i != (1<<n) ; i++) {
    String s = Integer.toBinaryString(i);
    while (s.length() != 3) {
        s = '0'+s;
    }
    System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)


NG.*_*NG. 1

如果你看看你生成的内容,它似乎是以二进制计数的。您将用二进制数数到 2^(n) - 1 并吐出这些位。