版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/83041002
java第三次作业
1、练习题
- 求斐波那契数列的前40项和。
- 用for循环产生20个随机数(10-20)。
- 输入一个数字,求他是几位数,并且是顺序输出还有逆序输出。
- 求一个数字的二进制数有几个1.
import java.util.*; //输入任意数必须定义这个。
public class HomeWork
{
/*
*求斐波那契数列的前40项的和???
* 1 1 2 3 5 8 13 ......
*/
public static int sun(int n)
{
int z=0;
int sum =0;
for(int i=0,x=1,y=0;i<n;i++,x=y,y=z) {
z = x + y;
sum += z;
}
return sum;
}
/*
* 用for循环产生20个随机数(10-20);
* a-b; Math.random() *(b-a)+a Math.random():[0,1) double
*/
public static void random(int n)
{
System.out.print("random:");
for(int i=1;i<=n;i++)
{
int random= (int)(Math.random()*(20-10)+10);// 放在for循环里面,每运行一次,随机一次,放在外面只随机一次。
System.out.print(random+";");
}
}
/*
*输入一个数字,求他是几位数,并且顺序输出,逆序输出
*/
public static void scanner(int n) {
String str = String.valueOf(n); //整型转字符串,也可以用 String str=b.toString();
System.out.println("length=" + str.length());
char[] ch = str.toCharArray(); //返回一个字符数组, 也就是将 String转换成 char[]
//parseint():就是把String转化成int 类型。
for (int i = 0; i <= str.length() - 1; i++) {
System.out.print(ch[i]);
}
System.out.println();
for (int i = str.length() - 1; i >= 0; i--) {
System.out.print(ch[i]);
}
}
/*
求一个数字的二进制数有几个1
*/
public static int math(int n)
{
int sum=0;
for(int i=1;i<=32;i++)
{
sum += n & 1;
n = n >>> 1;
}
return sum;
}
public static void main(String args [] )
{
Scanner sc=new Scanner(System.in);
int b=sc.nextInt(); //扫描类的定义。
scanner(b);
System.out.println();
System.out.println("sum="+sun(40));
random(20);
System.out.println();
System.out.println("sum="+math(15));
}
}
2、 课堂总结
1、if ; if…else;
public static int maxTwo(int a,int b)
if(a<b)
{
System.out.println(b);
}
else
{
System.out.println(a);
}
return a<b? b:a;//三元运算符和if...else可以相互替换。
public static int maxfour(int a,int b,int c, int d)//调用上面的maxTwo
{
return maxTwo(maxTwo(maxTwo(a,b),c),d);
}
2、 switch 语句
switch(666)
{
case 1:
System.out.println();
break;
case 666:
System.out.println();
break;
defauit:
System.out.println("six");
break;
/*不能做switch参数的类型
long n = 10000L;//不可以
float n = 12.5f;// 不可以
double n = 12.5;//不可以
*/
3、for 循环 for 嵌套
public static int fac(int n) {
int sum;
for(int x= 1; x <= n;i++) {
for(int i = 1; i <= x;i++){
sum= x*i;
System.out.print(sum+"="+x+"*"+i+";");
}
System.out.println();
}
4、扫描器 Scanner
//在类的前面一定要加上 import java.util.*
Scanner sc=new Scanner(System.in);
int b=sc.nextInt(); //扫描类的定义。
//int n = scanner.next();//遇到空格就结束
//String str2 = scanner.nextLine();识别空格