如何找到小于输入的最接近的完美正方形,或者完美正方形可以作为输入

我想制作一个程序来获取数字输入并找到最接近的完美正方形以确定正方形长度。因此,最接近的完美正方形必须小于输入。例如,如果输入是 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); 


        }

    }

}


慕少森
浏览 114回答 3
3回答

开心每一天1111

其他人指出的代码存在各种问题,我相信您会接受这些问题。不过,为了解决您的问题,我会做这样的事情。while 循环让您不断尝试新值,直到输入 -1。public static void main(String[] args) {&nbsp; &nbsp; System.out.println("Enter value:");&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; while (sc.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; boolean hasPerfectSquare = false;&nbsp; &nbsp; &nbsp; &nbsp; int input = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; if (input == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (int i = input; i > 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Math.floor(Math.sqrt(i)) == Math.sqrt(i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasPerfectSquare = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println((int) Math.sqrt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!hasPerfectSquare) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("No perfect square");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter value:");&nbsp; &nbsp; }}

森林海

如果我正确理解你的问题,我认为你想让 a1 的值减少直到达到 0。也许你需要for ( a1=a; a1 >= 0; a1--) {&nbsp; &nbsp; &nbsp; &nbsp; if (Math.floor(a1)==0)&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The largest square has side length" + a1);&nbsp;&nbsp;}更新编辑:从循环内的 a1 中删除了声明 int,因为它可能是另一个错误的来源(a1 的双重声明)。

倚天杖

正如 Elliott 在评论中提到的,从未进入循环。原因:a1被分配了a的值,然后您正在检查 a1. 这是不正确的,因此 for 循环甚至在第一次迭代之前就终止了。对于您要实现的目标,请使用:for (a1=a; a1 >= 0; a1--) {&nbsp; &nbsp; if (Math.floor(a1)==0)&nbsp; &nbsp; System.out.println("The largest square has side length" + a1);&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java