想请问后面的面积还有没有其他方法在上面写出来!感谢!
本帖最后由 MIQIWEI 于 2021-4-22 17:19 编辑编写一个程序,提示用户以浮点数的形式输入正方形的边的长度。程序然后打印一个正方形的面积。将结果打印到小数点后两位。注意:您可以假设用户输入的边长是有效的。
Test:
package lab1;
import java.util.Scanner;
public class demo2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter a side length:");
double length=input.nextDouble();
System.out.printf("Area of square with a side length of %.2f cm is .",length,length*length);
}
} 本帖最后由 肖-肖 于 2021-4-22 17:42 编辑
我这个跟你那个差不多,就是设置小数点不太一样~~
我感觉你的最后输出应该是:System.out.printf("Area of square with a side length of %.2f cm is %.2f",length,length*length);
已经试过了,可以的!
代码如下
/**
编写一个程序,提示用户以浮点数的形式输入正方形的边的长度。
程序然后打印一个正方形的面积。将结果打印到小数点后两位。注意:您可以假设用户输入的边长是有效的
*/
import java.util.Scanner;
public class demo2 {
public static void main(String[] args) {
//先定义一个面积的变量area double型的
double area = 0.0;
String area2;
System.out.print("Enter a side length:");
Scanner input=new Scanner(System.in);
double length=input.nextDouble();
//将面积给area
area = length*length;
//再将area保留2位小数点即可
area2 =String.format("%.2f",area);
System.out.printf("Area of square with a side length of %.2f cm is "+area2+".",length);
}
}
运行结果如下:
package com.lian.Test;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* @author :LSS
* @description: Calculate the area of the square given the variable length and save two decimal digits for the output
* @date :2021/4/20 11:50
*/
public class TestD {
public static void main(String[] args) {
//使用模板函数DecimalFormat定义保留两位小数的模板
DecimalFormat df = new DecimalFormat("######0.00");
Scanner input = new Scanner(System.in);
System.out.println("Enter a side length:");
double length = input.nextDouble();
//通过Math函数的pow平方方法计算出正方形的面积
double area = Math.pow(length, 2);
System.out.println("Area of square with a side length of " + df.format(length) + " cm is " + df.format(area) + " cm2");
}
}
肖-肖 发表于 2021-4-22 17:26
我这个跟你那个差不多,就是设置小数点不太一样~~
我感觉你的最后输出应该是:
已经试过了,可以的!
好滴~ 谢谢呢我大概知道了
页:
[1]