题目:使用for、do_while、while 3种循环语句分别实现输出1到40之间且是4的倍数的数,要求一行显示5个数据
自己写的:
public class Chp2_13{
public static void main(String[] args){
int i,j=1;
System.out.println("for循环");
//for循环
for(i=1;i<=50;i++){
if(i%4==0 && j!=5){
System.out.printf("%2d ",i);
j++;
}
else if(i%4==0 && j==5){
System.out.printf("%2d \n",i);
j=1;
}
}
//dowhile
System.out.println();
i=j=1;
System.out.println("dowhile循环");
do{
if(i%4==0 && j!=5){
System.out.printf("%2d ",i);
j++;
}
else if(i%4==0 && j==5){
System.out.printf("%2d \n",i);
j=1;
}
i++;
}while(i<=50);
//while
System.out.println();
i=j=1;
System.out.println("while循环");
while(i<=50){
if(i%4==0 && j!=5){
System.out.printf("%2d ",i);
j++;
}
else if(i%4==0 && j==5){
System.out.printf("%2d \n",i);
j=1;
}
i++;
}
}
}
运行结果:
for循环
4 8 12 16 20
24 28 32 36 40
44 48
dowhile循环
4 8 12 16 20
24 28 32 36 40
44 48
while循环
4 8 12 16 20
24 28 32 36 40
44 48
deepseek:
public class MultiplesOfFour {
public static void main(String[] args) {
int count = 0; // 计数器,用于控制每行输出的个数
for (int i = 1; i <= 50; i++) {
if (i % 4 == 0) { // 判断是否是4的倍数
System.out.print(i + "\t"); // 输出数字,用制表符分隔
count++;
if (count % 5 == 0) { // 每输出5个数字换行
System.out.println();
}
}
}
}
}
运行结果:
4 8 12 16 20
24 28 32 36 40
44 48
tips:制表符\n,5个一组count%5==0