所以我有这个程序:
for(int i=1;i<=5;i++){
int y=(int)Math.pow(4,i);
System.out.println(y);
}
我怎样才能打印出来:
4
16
64
256
1024
(在一位数之前它应该是3个空格, 2位2个空格,3位1空格。
谢谢:D
答案 0 :(得分:6)
System.out.printf("%4d\n", y);
答案 1 :(得分:0)
System.out.format("%4d\n", y);
唯一的问题是,如果您更改循环以生成超过4位的数字(例如,i <= 7),那么您将得到:
4
16
64
256
1024
4096
16384
然后,您需要计算您将生成的最大数字中的位数:
final int MAX_LOOP = 7;
for(int i=1; i<= MAX_LOOP; i++){
int y=(int)Math.pow(4,i);
System.out.format("%" + MAX_LOOP + "d\n", y);
}
结果:
4
16
64
256
1024
4096
16384