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?

So that printTruthTable(1) prints:

0

1

printTruthTable(3) prints:

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

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

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值