2014-01-15 211 views
1

我有一项任务,我很难搞清楚。矩形区域和边界


编写要求用户输入长度和矩形的宽度(均为正双精度浮点数),并打印的面积和周长的应用(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. 
+0

格式字符串语法在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 ...) –

回答

0

阅读文件关于String.format()format string syntax。这将帮助您找到正确的格式字符串以根据需要输出数字。

基本上你得有代码的最后两行:

System.out.println("The area of the rectangle is " + String.format("%.2f", area) + "."); 
System.out.println("The perimeter of the rectangle is " + String.format("%.2f", perimeter) + "."); 
+0

如果您使用'“%.2f “',你不需要关注整个'* 100',将其转换为'int',然后再除以100.0的业务。 –

+0

对。在这里很早... –

+0

非常感谢你们!字符串是我一直搞乱它:) – MalPal

1

您需要%.2fformat

System.out.printf("The perimeter of the rectangle is %.2f", 24.8); 

24.8只是为了测试,则可以替换用正确的表达。