在 while 循环中找到倍数。

huangapple go评论80阅读模式
英文:

Finding the multiple in while loop

问题

返回类型为 int,输入参数也为 int

我正在在 while 循环中生成随机整数,并且我正在检查该 int 是否是输入参数 int 的倍数,然后返回找到匹配的整数所用的尝试次数。

我希望在 while 循环中实现,而不是在 for 循环中。

public int findMul(int v){
    double random = Math.random();
    int numoftries = 0;

    while(v % random == 0){
        numoftries++;
    }
    return numoftries;
}

出于某种原因,当我在主方法中调用它然后执行它时,无论输入什么数字,它总是显示数字 0,我不知道如何修复。

英文:

The return type is int and the input parameters are also int.

I am generating random integers in the while loop and I am checking if that int is the multiple of the input parameter int and the return the number of tries it took to get that matched one.

And I want to do it in a while loop and not in a for loop.

public int findMul(int v){
    double random = Math.random();
    int numoftries = 0;

    while(v % random == 0){
        numoftries++;
    }
    return numoftries;
}

For some reason when I call it in the main method then execute it, it always shows the number 0 no matter what number and I don't know how to fix.

答案1

得分: 1

我要提出另一种方法来做这件事。

在生成下一个数字时,你应该只使用 rand.nextInt(v),因为它保证生成的数字比 v 小。生成比 v 大的数字永远不会是一个因子。

public int findMul(int v) {
    Random rand = new Random();
    int numoftries = 0;
    int random = rand.nextInt(v);
    while (true) {
        if (random == 0) {
            numoftries++;
            random = rand.nextInt(v);
            continue;
        }
        if (v % random == 0) {
            numoftries++;
            break;
        } else {
            numoftries++;
            random = rand.nextInt(v);
        }
    }
    return numoftries;
}

你原先的循环返回 0 是因为条件是 v%random==0,所以如果第一个生成的数字不是因子,它会立即返回 numoftries

你还需要在循环中每次生成一个新的数字,因为如果生成的数字不是因子,循环将会无限进行。

你可以像这样测试代码:

import java.util.Random;

public class RandomFactor {
    public static void main(String[] args) {
        RandomFactor x = new RandomFactor();
        System.out.println(x.findMul(1000)); // 1000 是测试用例
    }
}

有时,如果数字太小,有更高的可能性会生成 0,从而抛出 ArithmeticException。因此,我们添加了一个条件语句来防止这种情况发生。

如果你想使用 nextInt() 来实现相同的效果:

import java.util.Random;
import java.util.Scanner;

public class RandomFactor {
    public static void main(String[] args) {
        RandomFactor x = new RandomFactor();
        Scanner input = new Scanner(System.in);
        while (true) {
            try {
                System.out.print("Enter your guess: ");
                int guess = input.nextInt();
                System.out.println(x.findMul(guess));
            } catch (NumberFormatException e) {
                break;
            }
        }
    }
}

如果你必须使用 Math.random

import java.util.Scanner;

public class RandomFactor {
    public static int digits(int number) {
        String current = String.valueOf(number);
        return current.length();
    }

    public static int newrandom(int v) {
        return (int) (Math.random() * (digits(v) * 10));
    }

    public int findMul(int v) {
        int random = newrandom(v);
        int numoftries = 0;
        while (true) {
            if (random == 0) {
                numoftries++;
                random = newrandom(v);
                continue;
            }
            if (v % random == 0) {
                numoftries++;
                break;
            } else {
                numoftries++;
                random = newrandom(v);
            }
        }
        return numoftries;
    }

    public static void main(String[] args) {
        RandomFactor x = new RandomFactor();
        Scanner input = new Scanner(System.in);
        while (true) {
            try {
                System.out.print("Enter your guess: ");
                int guess = input.nextInt();
                System.out.println(x.findMul(guess));
            } catch (NumberFormatException e) {
                break;
            }
        }
    }
}

解释

因为 Math.random 返回一个双精度浮点数,所以我们需要生成一个与猜测数字相同位数的数字,然后将其转换为整数,以便进行比较。我们通过将其转换为字符串(digits 方法)然后将结果乘以 10 来实现。需要注意的是,这不是高效的方法,因为数字位数越多,猜测次数就越多。例如,如果我们猜测 5,它将从 0-9 进行猜测。如果我们猜测 10,它将从 10-100 进行猜测。

修正: 修复了一个致命错误,该错误会导致循环无限进行,因为如果随机数是 0,它不会重新生成一个数字。

英文:

I'm going to suggest another way to do it.

When you generate the next number, you should only use rand.nextInt(v), because it guarantees that the generated number is smaller than v. Generating a number greater than v will never be a factor.

public int findMul(int v) {
Random rand = new Random();
int numoftries = 0;
int random = rand.nextInt(v);
while (true) {
if(random==0) {
numoftries++;
random=rand.nextInt(v);
continue;
}
if(v%random==0) {
numoftries++;
break;
}else {
numoftries++;
random=rand.nextInt(v);
}
}
return numoftries;
}

Your loop was originally returning 0 because the condition was v%random==0, so if the first generated number wasn't a factor, it would instantaneously return numoftries

You also needed to generate a new number in the loop everytime, because then if the generated number wasn't a factor, it would be an infinite loop.

You can test the code like so:

import java.util.Random;
public class RandomFactor {
public int findMul(int v) {
Random rand = new Random();
int numoftries = 0;
int random = rand.nextInt(v);
while (true) {
if(random==0) {
numoftries++;
random=rand.nextInt(v);
continue;
}
if(v%random==0) {
numoftries++;
break;
}else {
numoftries++;
random=rand.nextInt(v);
}
}
return numoftries;
}
public static void main(String[] args) {
RandomFactor x = new RandomFactor();
System.out.println(x.findMul(1000));//1000 is the test case
}
}

Sometimes, if the number is too small, there is a higher possibility that it will generate 0, which will throw a ArithmeticException. So we add an if statement to prevent that from happening.

If you want to use nextInt() to achieve the same effect:

import java.util.Random;
import java.util.Scanner;
public class RandomFactor {
public int findMul(int v) {
Random rand = new Random();
int numoftries = 0;
int random = rand.nextInt(v);
while (true) {
if(random==0) {
numoftries++;
continue;
}
if(v%random==0) {
numoftries++;
break;
}else {
numoftries++;
random=rand.nextInt(v);
}
}
return numoftries;
}
public static void main(String[] args) {
RandomFactor x = new RandomFactor();
Scanner input = new Scanner(System.in);
while(true) {
try {
System.out.print("\nEnter your guess: ");
int guess = input.nextInt();
System.out.println(x.findMul(guess));
}catch(NumberFormatException e) {
break;
}
}
}
}

If you must use Math.random

import java.util.Scanner;
public class RandomFactor {
public static int digits(int number) {
String current = String.valueOf(number);
return current.length();
}
public static int newrandom(int v) {
return (int)(Math.random()*(digits(v)*10));
}
public int findMul(int v) {
int random = newrandom(v);
int numoftries = 0;
while (true) {
if(random==0) {
numoftries++;
random = newrandom(v);
continue;
}
if(v%random==0) {
numoftries++;
break;
}else {
numoftries++;
random=newrandom(v);
}
}
return numoftries;
}
public static void main(String[] args) {
RandomFactor x = new RandomFactor();
Scanner input = new Scanner(System.in);
while(true) {
try {
System.out.print("\nEnter your guess: ");
int guess = input.nextInt();
System.out.println(x.findMul(guess));
}catch(NumberFormatException e) {
break;
}
}
}
}

Explanation

Because Math.random returns a double, we need to generate a number with the same number of digits as the guess, and then cast to an integer so it can compare properly. We do this by converting it to a String (method digits) and then multiplying the result by 10 as Math.random returns a number between 0 and 1. However, keep in mind that this is not efficient, as the more digits the number has, the more guess it will make. For example, if we guess 5, it will guess from 0-9. If we guess 10, it will guess from 10-100.

EDIT: Fixed a fatal bug which causes it to loop forever, because if the random numuber was 0, it doesn't re-generate a number.

huangapple
  • 本文由 发表于 2020年9月27日 00:23:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64079994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定