如何显示未知数量数字的方表

我正在编写一个程序,计算素数序列,然后将它们显示在表格中。

程序要求用户输入 2 个整数:第一个是序列开始的数字,第二个是要找到的素数的数量。到这里,程序运行完美。问题是素数应该显示在“方形”表格中,这意味着如果可能的话,表格应该是完美的正方形。如果不可能,则行数和列数相差不应超过 1。

这是我尝试过的示例:

   int columns = 0;

   int rows = 0;

   int element = 0;


   rows = (int) Math.sqrt(numberOfPrimes);

   columns = (rows * rows) < numberOfPrimes ? rows + 1 : rows;


   if(numberOfPrimes%3 - 1.0 < 0.001)

   {

       columns = rows + 1;

       rows = rows + 1;

   }


   if (numberOfPrimes > 100)

   {

       columns = 10;

       if (rows * rows < numberOfPrimes)

       {

           rows = numberOfPrimes / 10;

       }


   }

   System.out.println(numberOfPrimes + " = [" + rows + "," + columns + "]");



   for (int r = 0; r < rows; r++) 

   {

      for (int c = 0; c < columns; c++)

      {

          System.out.printf("%6s", primesArray[element] + "\t");

          if (element == primesArray.length - 1)

          {

              break;

          }

          element++;

      }

      System.out.println();

   }

该表对于某些输入可以正确显示,但对于其他输入则不能正确显示。我知道这段代码是不正确的,但我不知道如何编写正确的代码来执行此操作。任何帮助,将不胜感激。


编辑:我将代码更新为现在的代码。该表对于奇数(例如 33)无法正常工作。它只打印 30 个数字,而不打印剩余的 3 个。我需要额外的一行来打印这些剩余的数字,即使该行不完整。我试图解决这个问题,但我创建了一个数组越界错误。另外,我添加了一个 if 语句,因为如果素数的数量超过 100,那么该表应该只有 10 列,并且不会是正方形。


编辑2:我设法解决了问题,并且更新了代码以显示解决方案。然而,我不得不使用休息时间,而我的教授不允许我们使用休息时间。一旦到达数组中的最后一个元素,是否有其他方法可以退出循环?


慕的地8271018
浏览 38回答 1
1回答

潇潇雨雨

这是一种方法&nbsp; &nbsp; int primeNumbersToBeFound = 33;&nbsp; &nbsp; int rows = (int) Math.ceil(Math.sqrt(primeNumbersToBeFound));&nbsp; &nbsp; int cols = rows;&nbsp; &nbsp; if (rows * (rows - 1) >= primeNumbersToBeFound) {&nbsp; &nbsp; &nbsp; &nbsp; cols--;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(primeNumbersToBeFound + " = [" + rows + "," + cols + "]");然后您可以循环打印素数的行和列。&nbsp; &nbsp; for (int r = 0; r < rows; r++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int c = 0; c < cols && element < primesArray.length; c++, element++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(primesArray[element]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java