[英]Need help for a specific java printing
所以我有这个程序:
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
System.out.printf("%4d\n", y);
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.