为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地8271018 2024-01-28 16:19:35
我正在编写一个程序,计算素数序列,然后将它们显示在表格中。程序要求用户输入 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:我设法解决了问题,并且更新了代码以显示解决方案。然而,我不得不使用休息时间,而我的教授不允许我们使用休息时间。一旦到达数组中的最后一个元素,是否有其他方法可以退出循环?
查看完整描述

1 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

这是一种方法


    int primeNumbersToBeFound = 33;


    int rows = (int) Math.ceil(Math.sqrt(primeNumbersToBeFound));

    int cols = rows;

    if (rows * (rows - 1) >= primeNumbersToBeFound) {

        cols--;

    }


    System.out.println(primeNumbersToBeFound + " = [" + rows + "," + cols + "]");

然后您可以循环打印素数的行和列。


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

        for (int c = 0; c < cols && element < primesArray.length; c++, element++) {

            System.out.print(primesArray[element]);

        }

        System.out.println();

    }


查看完整回答
反对 回复 2024-01-28
  • 1 回答
  • 0 关注
  • 29 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信