第六章-函数作业

E201_06_07_验证四位卡布列克数

题目要求:如题

解题思路:

1. 输入一个四位数

2. 判断输入的数是不是6174

3. 定义函数

4. 求出这个数的各个位

5. 运用冒泡转化

6. 循环输出6174

代码:

public class E201_06_07_验证四位卡布列克数 {

    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入四位不完全相同的数字为:");
            int num=sc.nextInt();
            while (num!=6174){
                int max=Max(num);//定义函数
                int min=Min(num);
                num=max-min;
                System.out.printf("%4d-%4d=%4d\n",max,min,num);
            }
        }

        private static int Min(int num) {
            int b1000=num/1000;//千位
            int b100 = num/100%10;//百位
            int b10 = num%100/10;//十位
            int b1 = num%10;//个位
            int [] a= {b1000,b100,b10,b1};
            int temp = 0;
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a.length - 1; j++) {
                    if (a[i] < a[j]) {
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }//冒泡循环 转换
                }
            }
            return num=a[0]*1000+a[1]*100+a[2]*10+a[3];
        }

        private static int Max(int num) {
            int b1000 = num / 1000;
            int b100 = num / 100%10;
            int b10 = num % 100 / 10;
            int b1 = num % 10;
            int [] a= {b1000, b100, b10, b1};
            int temp;
            for(int i = 0; i < a.length; i++ ){
                for(int j = 0; j < a.length - 1; j++){
                    if(a[i] > a[j]){
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }
            return num=a[0]*1000+a[1]*100+a[2]*10+a[3];
        }
    }

 

运行结果:

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页