我的代码是:
import java.util.Scanner;
public class AreaHexagon {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double side, area;
System.out.print("Enter the side:");
side = s.nextDouble();
area = ((3 * Math.pow(3, 0.5) / 2)) * Math.pow(side, 2);
System.out.print("The area of the hexagon is " + area);
}
}
我得到的错误信息是:对于6.6是侧面的长度,答案应该是113.17但是我得到了113.17219976,依此类推。我尝试添加 double roundOff = Math.round(side * 100)/ 100; ,但我无法使其正常运行。
答案 0 :(得分:5)
使用此:System.out.printf("The area of the hexagon is %.2f", area);
答案 1 :(得分:1)
要剪切一些小数部分,您可以使用
System.out.printf("%.2f", area);
道歉我已经复制了答案我编写了自己的函数,它在指定位置切割小数部分:
public static double cutDecimalPart(double number, int position) {
int power = (int) Math.pow(10, position);
int big = (int) (number * power);
return (double) big / power;
}
答案 2 :(得分:1)
import java.util.Scanner;
public class Hexagon {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double side, area;
System.out.print("Enter the side:");
side = s.nextDouble();
area = ((3.0 * Math.pow(3.0, 0.5) / 2.0)) * Math.pow(side, 2.0);
System.out.printf("The area of the hexagon is %.2f", area);
}
}
这是固定代码,运行顺畅。感谢您的帮助@ alex-chermenin& @沃伊切赫-kazior