题目:由三角形的三边长,求其面积。
输入格式:由空格分开的三个整数;输出格式:一个实数,保留两位小数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
double p = ((a + b +c)/2.0);
double s = Math.sqrt(p*(p - a)*(p - b)*(p - c));
System.out.println(String.format("%.2f", s));
scan.close();
}
}
题解中用到的数学公式是海伦公式,S=√p(p-a)(p-b)(p-c),其中p为三角形周长的一半,即p=(a+b+c)/2;在最后输出时,用到了String.format()方法,该方法用于写一个固定的字符串模板,在这里是保证输出的实数保留两位小数。