Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 矩形面积和周长_Java - Fatal编程技术网

Java 矩形面积和周长

Java 矩形面积和周长,java,Java,我有一项任务,我搞不清楚 编写一个应用程序(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. 我遇到的问题是

我有一项任务,我搞不清楚


编写一个应用程序(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.

阅读有关和的文档。这将帮助您找到正确的格式字符串,以便根据需要输出数字

基本上,您必须使用最后两行代码:

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) + ".");

您需要
格式的
%.2f

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

24.8
仅用于测试,您可以用正确的表达式替换它。

格式字符串语法在中解释,使用它的一种方法在java.lang.Object中解释…)如果您使用的是
“%.2f”
,您不必把整个
*100
,转换为
int
然后除以
100.0
业务。非常感谢大家!!字符串就是我把它弄乱的地方:)在StackOverflow上的“谢谢你”的意思是向上投票/接受帮助你的答案:-)哦!我刚试过,它说我必须先有15岁的名声。我一拿到15分就会投票!