Subtracting Random numbers [duplicate]

2019-03-06 06:11发布

This question already has an answer here:

I'm making a game where the user must solve a simple subtraction but the result must be a positive whole number. I managed to do everything but for some reason the answer is sometimes negative and I'm not sure how to fix it

import java.util.Random;
import java.util.Scanner;
public class Subtraction {
  public static void main(String[] args) {
    Random r = new Random();

    final int MAX = 10;
    // get two random numbers between 1 and MAX
    int num1 = r.nextInt(MAX) - 1;
    int num2 = r.nextInt(MAX) - 1;

    int total = (num1 - num2);

    // display a question
    System.out.printf("What is your answer to %d - %d = ?%n", num1, num2);

    // read in the result
    Scanner stdin = new Scanner(System.in);
    int ans = stdin.nextInt();
    stdin.nextLine();

    // give an reply
    if (ans == total) {
      System.out.println("You are correct!");
    } else {
      System.out.println("Sorry, wrong answer!");
      System.out.printf("The answer is %d + %d = %d%n", num1, num2, (num1 - num2));
    }

  }
}

标签: java random
6条回答
Juvenile、少年°
2楼-- · 2019-03-06 06:37

Generate your first value with room at the bottom for a second value to be subtracted, and the second one from a range bounded by the first:

int num1 = r.nextInt(MAX - 1) + 2;  // produces values from 2 to MAX, inclusive
int num2 = r.nextInt(num1 - 1) + 1; // produces values from 1 to (num1 - 1), inclusive

The first number will always be strictly larger than the second, by construction, so the difference will always be a positive integer.

查看更多
不美不萌又怎样
3楼-- · 2019-03-06 06:37

The code at the very heart of your program is wrong:

// get two random numbers between 1 and MAX
int num1 = r.nextInt(MAX) - 1;
int num2 = r.nextInt(MAX) - 1;

r.nextInt(MAX) returns a number between 0 (inclusive) and MAX (exclusive). Your code subtracts one from it, so you get a number in the range [−1, MAX−2].

Since you want it to be a simple subtraction where all numbers are in the range [1, MAX], you have to generate them that way. The general form of the subtraction is:

result = num1 − num2

This equation has the following constraints:

  • 1 <= result <= MAX
  • 1 <= num1 <= MAX
  • 1 <= num2 <= MAX
  • result < MAX, since otherwise num2 would have to be 0
  • 1 < num1, since otherwise the result would become negative
  • num2 < MAX, since otherwise result would have to be larger than MAX

This leaves the following allowed ranges:

  • 1 <= result <= MAX − 1
  • 2 <= num1 <= MAX
  • 1 <= num2 <= MAX − 1
  • num2 <= num1 - 1

To generate these numbers, the code has to look like this:

int num1 = randomBetween(2, MAX);
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = randomBetween(1, maxNum2);

Now what is randomBetween? You have to define it:

randomBetween(min, max) ≡ r.nextInt(max + 1 - min) + min

Together, this is:

int num1 = r.nextInt(MAX + 1 - 2) + 2;
int maxNum2 = Math.min(MAX - 1, num1 - 1);
int num2 = r.nextInt(maxNum2 + 1 - 1) + 1;
int result = num1 - num2;
assert 1 <= result && result <= MAX;
查看更多
贪生不怕死
4楼-- · 2019-03-06 06:39

Two possible solutions: Just change your total line with a condition to subtract the larger one from the smaller one (unless they're the same, in which case you'll get 0)

 int total = (num1 > num2) ? (num1 - num2) : (num2 - num1);

Or just use the absolute value:

 int total = java.lang.Math.abs(num1 - num2);

Change the printf as well:

 System.out.printf("What is your answer to %d - %d = ?%n", (num1 > num2) ? num1 : num2, (num1 > num2) ? num2 : num1);

The conditionals are just making sure that the bigger number comes before the smaller number, or if they happen to be equal, that they are both listed.

Check out http://www.cafeaulait.org/course/week2/43.html for a more thorough explanation of the ? operator.

查看更多
SAY GOODBYE
5楼-- · 2019-03-06 06:39

Since you know the result must be positive, I would start with the result

int total = r.nextInt(MAX) + 1;
int num2 = r.nextInt(MAX - total + 1);

int num1 = total + num2;

This way you can be sure that num1 - num2 will always be positive.

查看更多
贪生不怕死
6楼-- · 2019-03-06 06:41
package optinalTest;

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class Subtraction {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            randomNumber();
        }

    }

    private static void randomNumber() {
        // get two random numbers between 1 and MAX
        int num1 = ThreadLocalRandom.current().nextInt(10000, 9999998);
        int num2 = ThreadLocalRandom.current().nextInt(num1 + 1, 9999999);

        int total = (num2 - num1);

        // display a question
        System.out.printf("What is your answer to %d - %d = ?%n", num2, num1);

        // read in the result
        Scanner stdin = new Scanner(System.in);
        int ans = stdin.nextInt();
        stdin.nextLine();

        // give an reply
        if (ans == total) {
            System.out.println("You are correct!");
        } else {
            System.out.println("Sorry, wrong answer!");
            System.out.printf("The answer is %d - %d = %d%n", num2, num1, (num2 - num1));
        }
    }
}
查看更多
可以哭但决不认输i
7楼-- · 2019-03-06 06:43

Well, with two random numbers in the same range, in random order, either cold be larger and the subtraction could be negative. Either fix how you get the numbers, or fix how they are ordered, or fix how you get their difference; any of these will do the job.

查看更多
登录 后发表回答