任务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);
}
}
}
- 运行样式