java – RandomGenerator – 失去50%的飞机模拟
发布时间:2020-05-28 20:22:15 所属栏目:Java 来源:互联网
导读:我正在研究一个我有点困惑的问题.问题是假设你在二战期间是英国空军的将军.你还有100架飞机来保卫英国.每次执行任务时,每架飞机都有50%的机会被德国防空炮击落,所以每次任务都会损失大约一半的飞机.你必须编写一个程序来估计每次任务后将有多少架飞机存活,以
|
我正在研究一个我有点困惑的问题.问题是假设你在二战期间是英国空军的将军.你还有100架飞机来保卫英国.每次执行任务时,每架飞机都有50%的机会被德国防空炮击落,所以每次任务都会损失大约一半的飞机.你必须编写一个程序来估计每次任务后将有多少架飞机存活,以及你可以运行多少任务直到所有飞机都被击落. 我的程序不起作用,我不知道它有什么问题,所以我猜英格兰遇到了麻烦.我试图用两个while循环来解决这个问题.外部while循环表示只要你有飞机就可以将它们发送给另一个任务.内部while循环模拟实际任务.在while循环存在之后,平面的总数现在是幸存的平面. import acm.program.*;
import acm.util.*;
public class MissionPlanes extends ConsoleProgram{
public void run(){
int planes = 100; /* total number of planes */
int suvPlanes = 0; /* surviving planes */
int mission = 0; /* total number of missions */
int planeCounter = 0; /* keeps track of the planes flying over the anti plane gun */
while (planes > 0){
while(planeCounter < planes){
planeCounter++;
if(rgen.nextBoolean()){ /* I've tried rgen.nextBoolean() with paramaters and with no paramaters */
suvPlanes += 1;
}
}
planes = suvPlanes;
mission++;
println("The total number of surviving planes you have is " + planes + "after" + missoin + "missions");
}
}
private RandomGenerator rgen = RandomGenerator.getInstance();
}
解决方法您必须在外循环中将planeCounter重置为0. suvPlanes也是如此:while (planes > 0){
planeCounter = 0;
suvPlanes = 0;
// ... remaining stuff
如果你不在这个循环的第二次迭代中这样做,你将最终得到planeCounter> = plane,这样你就不会执行内循环了.另一方面,suvPlanes不会被重置为0,因此平面将永远保持等于第一个周期中suvPlanes的值,因此您的外部循环将永远不会终止. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读
