项目二_任务1_(三)拓展练习:任务


任务1:由卡号计算幸运数

  • 员工卡号是四位整数 [1000,9999],各位数字的和就是参加抽奖活动的幸运数字,比如 4512 , 4 + 5 + 1 + 2 = 12 ,幸运数字就是 12。
  • 输入员工卡号,编程计算该员工的幸运数字

方法一:直接拆分整数

  • 源代码
/**
 * 功能:计算幸运数(直接拆分)
 * 作者:小梁aixj
 * 日期:2022年05月17日
 */

public class Lucking {
    public static void main(String[] args) {
        //定义部分
        int a,p1,p2,p3,p4,sum;

        //输入部分
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个四位整数:");
        a = sc.nextInt();

        //拆分部分
        p1 = a % 10;//个位
        a = a / 10;
        p2 = a % 10;//十位
        a = a / 10;
        p3 = a % 10;//百位位
        a = a / 10;
        p4 = a;//千位

        //求和部分
        sum = p1+p2+p3+p4;

        //输出部分
        System.out.println("您的幸运数是:" + sum +"。");

    }
}
  • 运行样式
    在这里插入图片描述

方法二:转换成字符串来处理

  • 源代码
/**
 * 功能:计算幸运数(转换成字符串)
 * 作者:小梁aixj
 * 日期:2022年05月17日
 */
public class Lucky01 {
    public static void main(String[] args) {
        //定义部分
        int a,p1,p2,p3,p4,sum;

        //输入部分
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个四位整数:");
        a = sc.nextInt();

        //拆分部分
        String str = String.valueOf(a);
        p1 = (int)str.charAt(0) - 48;//个位
        p2 = (int)str.charAt(1) - 48;//十位
        p3 = (int)str.charAt(2) - 48;//百位
        p4 = (int)str.charAt(3) - 48;//千位

        //输出部分
        sum = p1+p2+p3+p4;
        System.out.println(p1);
        System.out.println("您的幸运数是:" + sum +"。");
    }
}

  • 运行样式
    在这里插入图片描述

  • 计算机科学家Wirth在上个世纪70年代提出一个经典公式:程序 = 数据结构 + 算法,数据结构是程序的基础,算法是程序的灵魂。

任务2:解一元二次方程

要求

在这里插入图片描述

  • 源代码
/**
 * 功能:解一元二次方程
 * 作者:小梁aixj
 * 日期:2022年05月15日
 */
public class CalcTwo {
    public static void main(String[] args) {
        int a,b,c;
        double dt,x1,x2;
        Scanner sc = new Scanner(System.in);

        System.out.print("a = ");
        a = sc.nextInt();
        System.out.print("b = ");
        b = sc.nextInt();
        System.out.print("c = ");
        c = sc.nextInt();
        dt = (b * b - 4*a*c);

        if (dt < 0) {
            System.out.println("△不能小于零!");
        } else if (dt >= 0) {
            x1 = -b+(Math.sqrt(dt));
            x2 = -b-(Math.sqrt(dt));
            System.out.println("x1 = "+ x1 + ",x2 = "+x2);
        }
    }
}
  • 运行样式
    在这里插入图片描述在这里插入图片描述

​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁辰兴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值