我有一项任务,我很难搞清楚。矩形区域和边界
编写要求用户输入长度和矩形的宽度(均为正双精度浮点数),并打印的面积和周长的应用(Rectangle.java)长方形。当用户输入7.9和4.5,你的程序的输出应该看起来就像下面:
Enter the length and the width of a rectangle: 7.9 4.5
The area of the rectangle is 35.55.
The perimeter of the rectangle is 24.80.
我有带来的是长方形的周长的输出了两个麻烦的部分小数位,包括“0”。我一直试图弄清楚这么久。我知道必须有一个简单有效的方法来做到这一点,否则它将不会被分配给我们作为我们的第二个Java作业。如果是将其格式化为%2d,我不知道如何将其应用于我所拥有的。我真的很感谢你的帮助!
这里是我到目前为止有:
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and the width of a rectangle: ");
double length = input.nextDouble();
double width = input.nextDouble();
double area = (length * width);
double perimeter = (length * 2 + width * 2);
System.out.println("The area of the rectangle is " + (int)(area * 100)/100.0 + ".");
System.out.println("The perimeter of the rectangle is " + (int)(perimeter * 100)/100.0 + ".");
}
}
我的输出:
Enter the length and the width of a rectangle: 7.9 4.5
The area of the rectangle is 35.55.
The perimeter of the rectangle is 24.8.
格式字符串语法在http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax解释和一个方式来使用它在http解释:// docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#format(java.lang.String,java.lang.Object ...) –