java输出小数的四舍五入

难过难过难过

5. 设计名为Rectangle的类表示矩形,

成员变量:widthheight表示矩形的宽和高,其数据类型为double,默认值是1.0

成员变量:color表示矩形的颜色,其数据类型为String默认颜色为白色;

构造方法:无参数的构造方法Rectangle(),其功能是创建默认的矩形;

构造方法:带三个参数的构造方法Rectangle(double width,double height,String color),其功能是创建指定大小和颜色的矩形

成员方法:getWidth()getHeight()getColour()功能是获取矩形的相应信息;

成员方法:setWidth()setHeight()setColour()功能是修改矩形相应的信息

成员方法:getArea() 计算矩形的面积并返回其值;

    成员方法:getPerimeter()计算矩形的周长并返回其值;

编写一个测试程序,创建两个Rectangle对象,设置第一个对象的宽为4,高为40,颜色为黄色,第二个对象的宽为3.5,高为35.9,颜色为红色。显示两个对象的属性并将它们的面积和周长输出。

import java.util.*;
class Rectangle{
	private double width,height;
	private String color=new String();
	public Rectangle(){
		width=1.0;
		height=1.0;
		color="白色";
	}
	public Rectangle(double width,double hight,String color){
		this.width=width;
		this.height=hight;
		this.color=color;
	}
	public double getWidth(){
		return width;
	}
	public double getHeight(){
		return height;
	}
	public String getColor(){
		return color;
	}
	public void setWidth(double a){
		width=a;
	}
	public void setHeight(double a){
		height=a;
	}
	public void setColor(String a){
		color=a;
	}
	public double getArea(){
		return width*height;
	}
	public double getPerimeter(){
		return (width+height)*2;
	}
}

public class TestRectangle {
	public static void main(String args[]){
		Rectangle rec1=new Rectangle(4.0,40.0,"黄色");
		Rectangle rec2=new Rectangle(3.5,35.9,"红色");
		System.out.println("rec1: "+"宽:"+rec1.getWidth()+",高:"+rec1.getHeight()+",颜色:"+rec1.getColor()+",面积:"+rec1.getArea()+",周长:"+rec1.getPerimeter());
		System.out.println("rec2: "+"宽:"+rec2.getWidth()+",高:"+rec2.getHeight()+",颜色:"+rec2.getColor()+",面积:"+rec2.getArea()+",周长:"+rec2.getPerimeter());
		System.out.printf("%.2f\n",165.655);//方法一
		java.text.DecimalFormat df=new java.text.DecimalFormat("#.##");//方法二
		System.out.println(df.format(165.655));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值