这是我在这里发表的第一篇文章。
我一直在寻找 Daniel Liang 所著《Java 编程简介》(第 10 版)一书中我试图做的一个练习的答案。
我认为我的大部分代码都是正确的,但我的答案与书籍控制台示例不同。我使用了书上告诉我使用的数学公式,当我在控制台中输入相同的数字时,我的答案并不相同。
更具体地说,它要求我使用这个公式来计算面积:面积=平方根(3)/4(边长)^2
我可能在添加该公式时做错了什么,但搜索周围的人一直建议使用相同的东西(Math.sqrt(3))
这是我的代码,如有任何帮助,请采纳:
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) {
// Create new scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter length and height of the Equilateral triangle
System.out.print("Enter length of the sides" +
" and height of the Equilateral triangle: ");
double lengthOfSides = input.nextDouble();
// Calculate the area & display to user
double area = (Math.sqrt(3) / 4) * (Math.pow(lengthOfSides, 2));
System.out.println("The area is: " + area);
//Calculate the volume & display to user
double volume = area * lengthOfSides;
System.out.println("The volume of the Triangular prism is: " + volume);
input.close();
}
}
忘记添加我得到的和书上得到的:
我明白了 输入等边三角形的边长和高度:3,5 面积为:5.304405598179686 三棱柱的体积为:18.565419593628903
本书: 输入等边三角形的边长和高度:3,5 面积为:3.89 三棱柱的体积为:19.48
最佳答案
我认为您误解了本书提供的内容。如果您使用“3”而不是“3,5”作为输入,则该公式有效。
(sqrt(3)/4) * ( 3 ^ 2) = 3.89711431703
您应该让程序要求输入边长,而不是三角形的边长和高。
如果需要,您可以在不同的扫描仪输入上询问三角形的高度。
关于java - 练习 2.2 的数学公式 - 梁丹尼尔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886218/