您的位置:首页 > 其它

2014年4月17日星期四学习历程-斐波那契数列、付款、圆与圆之间程序编写

2014-04-17 00:53 218 查看
一、斐波那契数列
代码:

import java.util.Scanner;

//实现斐波那契数列1 1 2 3 5 8 13 21 34 55 89 ......
//经过运算后发现到49个数列时会发生数据丢失,所以int数据类型不够用
public class Fblq {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("请输入你要选择的数列级别:");
int num = scan.nextInt();
scan.close();

System.out.println("你输入的级别对应的斐波那契数是:"+f(num));
System.out.println("f(6)="+f(6));
System.out.println("f(8)="+f(8));
System.out.println("f(48)/f(49)="+(double)(f(48)/f(49)));
}

//建立一个计算斐波那契数列的函数
public static long f(int n){//返回值类型也更改为long
long sum = 0;//目标数列中数值先定义为0,更改数据类型为long
long[] arr = new long
;//建立一个数组来存储每一个数值,存储数据也改为long

if(n>=3){//数组中0、1、2直接从2位计算
arr[0] = 1l;
arr[1] = 1l;
for(int i=2;i<arr.length;i++){
arr[i] = arr[i-1]+arr[i-2];//当前数值等于前两位的数值之和
}
sum = arr[arr.length-1];//数组最后最大的数值便是所求的数列最后一个
}else {
sum = 1;//0、1时直接定义为0
}
return sum;//返回值
}
}

二、付款:
代码:

import java.util.Scanner;

//支付饮料,若饮料双瓶购买其中一个半价
public class MoneyPay {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);//输入
System.out.println("请输入饮料的单价:");
double price = scan.nextDouble();//输入单价
System.out.println("饮料单价为:"+price);
System.out.println("请输入饮料的数量:");
int num = scan.nextInt();//输入饮料数量
System.out.println("饮料数量为:"+num);
scan.close();

double count = getMoney(price,num);//调用方法计算费用金额
System.out.println("需要支付的饮料金额为:"+count);
}

//建立一个计算付款金额的方法
public static double getMoney(double price,int num){
double count = 0;
if(num%2!=0){
count = (num/2+1)*price+num/2*0.5*price;//数量为奇数时全价多一个
}else{
count = num/2*price+num/2*0.5*price;//数量为偶数时全价半价均等
}
return count;
}

}

三、球类的建立和判断:
代码:

//在坐标系中建立一个球,通过x、y坐标,半径r定义,
//然后在类中定义一个方法和另外一个球比较是否接触
//在测试类中创建两个对象,并判断是否相撞接触
public class BallTest {
public static void main(String[] args){
Ball b1 = new Ball(3,6,5);//创建一个对象b1
Ball b2 = new Ball(4,9,6);//创建一个对象b2
boolean flag = b1.ballGo(b2);//判断对象是否相撞
//输出结果,当然在类中也可以完成
if(flag)
System.out.println("砰");
else
System.out.println("nothing");
}
}
//定义一个Ball的类
class Ball{
//定义坐标和半径为成员变量
int x;
int y;
int r;

//定义构造方法对成员变量赋值
public Ball(int x,int y,int r){
this.x = x;
this.y = y;
this.r = r;
}

//定义BallGo方法判断两个Ball对象是否相撞
public boolean ballGo(Ball other){
//计算圆与圆心之间的距离
double l = Math.sqrt((this.x-other.x)*(this.x-other.x)+(this.y-other.y)*(this.y-other.y));
//两个圆之间的半径和
double r2 = this.r+other.r;
if(l>r2)//未相撞
return false;
else
return true;//相撞

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐