【问题标题】:How do I find the closest perfect square less than the input, or the perfect square can be the input如何找到小于输入的最接近的完美平方,或者完美平方可以是输入
【发布时间】:2019-11-23 02:35:21
【问题描述】:

我想编写一个程序来获取数字输入并找到最接近的完美正方形来确定正方形长度。因此,最接近的完美平方必须小于输入。比如输入8,正方形的最大边长是2。问题是程序会要求我输入一个数字,但之后没有输出任何东西。它还说我有一个重复的局部变量 a1。

import java.util.Scanner;  
public class J1 {

    public static void main(String[] args) {

        int a;
        int a1;

        Scanner number = new Scanner(System.in);
        System.out.println("Number: ");
        a = number.nextInt(); 
        int n = (int) Math.sqrt(a1); 

        /* remove int from a1 */
        for ( int a1=a; a1<a; a1--) {

            if (Math.floor(a1)==0)
            System.out.println("The largest square has side length" + a1); 

        }
    }
}

【问题讨论】:

  • 您已经告诉我们您想要做什么,但没有告诉我们您的代码尝试遇到了什么问题。您在问题标题中提到了第 13 行,但不要在代码中标注这是哪一行。请编辑您的问题,以更清楚地说明问题所在,以便您有更好的机会帮助您。
  • 您应该非常仔细查看for (int a1=a; a1&lt;a; a1--)中的循环条件 - 您的循环永远不会进入。
  • 我已经澄清了我的问题
  • 你能澄清一下@ElliottFrisch 的意思吗
  • 你给变量 n 赋值,但从不使用它。那是你的意思吗?

标签: java for-loop perfect-square


【解决方案1】:

其他人指出的代码存在各种问题,我相信您会接受这些问题。不过,为了解决您的问题,我会做这样的事情。 while 循环可让您不断尝试新值,直到输入 -1。

public static void main(String[] args) {
    System.out.println("Enter value:");
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        boolean hasPerfectSquare = false;
        int input = sc.nextInt();
        if (input == -1) {
            break;
        }
        for (int i = input; i > 0; i--) {
            if (Math.floor(Math.sqrt(i)) == Math.sqrt(i)) {
                hasPerfectSquare = true;
                System.out.println((int) Math.sqrt(i));
                break;
            }
        }
        if (!hasPerfectSquare) {
            System.out.println("No perfect square");
        }
        System.out.println("Enter value:");
    }
}

【讨论】:

    【解决方案2】:

    正如 Elliott 在评论中提到的,循环永远不会进入。 原因:a1 被分配了 a 的值,然后您正在检查是否为 a1。这不是真的,因此 for 循环甚至在第一次迭代之前就终止了。对于您想要实现的目标,请使用:

    for (a1=a; a1 >= 0; a1--) {
        if (Math.floor(a1)==0)
        System.out.println("The largest square has side length" + a1); 
    }
    

    【讨论】:

    • 我将如何解决这个问题,我使 a 等于 a1 并开始递减,以确定与 a 表示的输入最接近的完美平方。
    • for(int a1 = a; a1 > 0; a1--)
    【解决方案3】:

    如果我正确理解您的问题,我认为您想让 a1 的值减小直到达到 0。也许您需要

    for ( a1=a; a1 >= 0; a1--) {
            if (Math.floor(a1)==0)
            System.out.println("The largest square has side length" + a1); 
     }
    

    更新编辑:从循环内的 a1 中删除声明 int,因为它可能是另一个错误的来源(a1 的双重声明)。

    【讨论】:

    • 它说for循环中有一个重复的局部变量a1
    • @Cleo 我更新了我的初始答案以解决“重复的局部变量”问题。
    猜你喜欢
    • 2017-12-23
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多