第四章第六题(圆上的随机点)(Random points on a circle)
-
4.6(圆上的随机点)编写一个程序,产生一个圆心位于(0,0)、半径为40的圆上面的三个随机点,显示由这三个随机点组成的三角形的三个角的度数。(提示:产生0~2pi之间的一个以弧度为单位的随机角度alpha,则由这个角度所确定的点为(rcos(alpha),r*sin(ahlpha))。)
4.6(Random points on a circle) Write a program that generates three random points on a circle centered at (0, 0) with radius 40 and displays three angles in a triangle formed by these three points, as shown in Figure 4.4a. (Hint: Generate a random angle a in radians between 0 and 2π, as shown in Figure 4.4b and the point determined by this angle is (rcos(alpha),r*sin(ahlpha)).)
-
参考代码:
package chapter04;
public class Code_06 {
public static void main(String[] args){
double x1, y1, x2, y2, x3, y3;
double angleA,angleB,angleC,alpha;
double a,b,c;
alpha = Math.random() * (2 * Math.PI);
x1 = 40 * Math.cos(alpha);
y1 = 40 * Math.sin(alpha);
alpha = Math.random() * (2 * Math.PI);
x2 = 40 * Math.cos(alpha);
y2 = 40 * Math.sin(alpha);
alpha = Math.random() * (2 * Math.PI);
x3 = 40 * Math.cos(alpha);
y3 = 40 * Math.sin(alpha);
a = Math.sqrt(Math.pow(x1 - x2, 2)+Math.pow(y1 - y2, 2));
b = Math.sqrt(Math.pow(x1 - x3, 2)+Math.pow(y1 - y3, 2));
c = Math.sqrt(Math.pow(x3 - x2, 2)+Math.pow(y3 - y2, 2));
angleA = Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c)));
angleB = Math.toDegrees(Math.acos((b * b - a * a - c * c) / (-2 * a * c)));
angleC = Math.toDegrees(Math.acos((c * c - b * b - a * a) / (-2 * b * a)));
System.out.printf("The first angle in degree is %.2f\n", angleA);
System.out.printf("The second angle in degree is %.2f\n", angleB);
System.out.printf("The third angle in degree is %.2f", angleC);
}
}
- 结果显示:
The first angle in degree is 69.03
The second angle in degree is 22.23
The third angle in degree is 88.74
Process finished with exit code 0