我有一个任务:我需要对一栋大楼中的 100 个公寓进行编号,但它们不应该是编号 3 和 5(13、15、23、25 等)。所以会有编号为 101、104 等的公寓。问题是我应该只使用循环(for 或 while)和 if 语句来做到这一点。
int counter = 0;
for (int i = 1; i < 100; i++) {
if (i / 10 == 3 || i % 10 == 3 || i / 10 == 5 || i % 10 == 5) {
continue;
}
System.out.print(i + " ");
counter++;
}
System.out.println(counter);
这很笨拙,我只有最多 100 的编号,而不是 100。总的来说,我现在只有 63 套公寓编号
您不应该通过
i
而是通过 counter
来测试状况:
int counter = 0;
for (int i = 1; counter < 100; i++) {
if (i / 10 == 3 || i % 10 == 3 || i / 10 == 5 || i % 10 == 5) {
continue;
} else {
++counter;
System.out.println(counter + ": " + i);
}
}