用Java生成真值表 [英] Generating truth tables in Java

查看:1231
本文介绍了用Java生成真值表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to print some truth tables as part of a school assignment. How can I generate a dynamic size truth table in Java?

这样 printTruthTable(1)打印:

0
1

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

依此类推。我一直在尝试使用递归来实现它,但我无法正确使用它。

And so on. I have been trying to implement it using recursion, but I just can't get it right.

推荐答案

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

here's my take on your problem, all written nice and tight in a small class, just copy/paste

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

notice how I used modulo2 (the % sign) to get 0's and 1's from the loop indices

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
    }
}

这篇关于用Java生成真值表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆