题目
从键盘读取圆柱底面半径和高,计算并输出圆柱的体积,结果保留两位小数。
公式:V=πr² h
代码内容
exercise包下的CylinderDemo类
package exercise;
import java.util.Scanner;
import java.text.DecimalFormat;
import static java.lang.Math.*;
public class CylinderDemo {
/**
* @param args
* @content : 从键盘读取圆柱底面半径和高,计算并输出圆柱的体积;
*/
public static void main(String[] args) {
double radius, high, volume; //radius:半径 high:高 volume:体积
Scanner sc = new Scanner(System.in); //创建Scanner对象sc
System.out.print("请输入底面半径:");
radius = sc.nextDouble(); //键盘录入半径
System.out.print("请输入高:");
high = sc.nextDouble(); //键盘录入高
volume = 3.14 * pow(radius, 2) * high; //计算圆柱体体积
DecimalFormat df = new DecimalFormat("#.00"); //保留两位小数
System.out.println("圆柱体的体积为:" + df.format(volume));
}
}
运行结果
总结
保留两位小数需要用到DecimalFormat类格式为DecimalFormat df = new DecimalFormat("#.00")
并且需要导入import java.text.DecimalFormat;还要用的DecimalFormat类中的format()方法
键盘录入需要用到Scanner类格式为Scanner sc = new Scanner(System.in);
录入双精度浮点型数据需要用到Scanner类中的nextDouble()方法