java – RandomGenerator – 失去50%的飞机模拟

前端之家收集整理的这篇文章主要介绍了java – RandomGenerator – 失去50%的飞机模拟前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究一个我有点困惑的问题.问题是假设你在二战期间是英国空军的将军.你还有100架飞机来保卫英国.每次执行任务时,每架飞机都有50%的机会被德国防空炮击落,所以每次任务都会损失大约一半的飞机.你必须编写一个程序来估计每次任务后将有多少架飞机存活,以及你可以运行多少任务直到所有飞机都被击落.

我的程序不起作用,我不知道它有什么问题,所以我猜英格兰遇到了麻烦.我试图用两个while循环来解决这个问题.外部while循环表示只要你有飞机就可以将它们发送给另一个任务.内部while循环模拟实际任务.在while循环存在之后,平面的总数现在是幸存的平面.

  1. import acm.program.*;
  2. import acm.util.*;
  3.  
  4. public class MissionPlanes extends ConsoleProgram{
  5. public void run(){
  6.  
  7. int planes = 100; /* total number of planes */
  8. int suvPlanes = 0; /* surviving planes */
  9. int mission = 0; /* total number of missions */
  10. int planeCounter = 0; /* keeps track of the planes flying over the anti plane gun */
  11.  
  12.  
  13. while (planes > 0){
  14.  
  15. while(planeCounter < planes){
  16. planeCounter++;
  17. if(rgen.nextBoolean()){ /* I've tried rgen.nextBoolean() with paramaters and with no paramaters */
  18. suvPlanes += 1;
  19. }
  20. }
  21. planes = suvPlanes;
  22. mission++;
  23. println("The total number of surviving planes you have is " + planes + "after" + missoin + "missions");
  24. }
  25. }
  26. private RandomGenerator rgen = RandomGenerator.getInstance();
  27. }

解决方法

您必须在外循环中将planeCounter重置为0. suvPlanes也是如此:
  1. while (planes > 0){
  2. planeCounter = 0;
  3. suvPlanes = 0;
  4. // ... remaining stuff

如果你不在这个循环的第二次迭代中这样做,你将最终得到planeCounter> = plane,这样你就不会执行内循环了.另一方面,suvPlanes不会被重置为0,因此平面将永远保持等于第一个周期中suvPlanes的值,因此您的外部循环将永远不会终止.

猜你在找的Java相关文章