我希望我的代码每行打印10个数字并计算有多少个数字。我也希望能够找到最大数量。我在弄清楚如何找到最大值时遇到了麻烦。这是我的代码。
int valCount = 0;
int numCount =0;
while (startingNum > 1) {
int count = 0;
System.out.print(startingNum + " ");
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
numCount++;
} else {
startingNum = (startingNum*3) +1;
numCount++;
}
}
答案 0 :(得分:0)
您可以使用一个计数器,在每次打印时增加它,当您达到10的倍数时,换一行,也为了对齐不同的元素,我建议使用printf
,这里我设置为{ {1}},因为最大位数为4位数字,如果最高位数达到6位数字,请使用%5d
%7d
Demo code
将给您:
int valCount = 0;
while (startingNum > 1) {
System.out.printf("%5d", startingNum);
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
} else {
startingNum = (startingNum*3) +1;
}
}
System.out.printf(" 1");
答案 1 :(得分:0)
这是正确的代码:
public static void main(String[] args) {
int startingNum = 27;
int counter = 0;
while (startingNum > 1) {
counter++;
System.out.print(startingNum + " ");
if (counter % 10 == 0)
System.out.println();
if (startingNum % 2 == 0) {
startingNum = startingNum / 2;
} else {
startingNum = (startingNum * 3) + 1;
}
}
System.out.println(1);
}