gpt4 book ai didi

java - 减去随机数

转载 作者:行者123 更新时间:2023-12-01 10:01:40 27 4
gpt4 key购买 nike

我正在制作一个游戏,用户必须解决一个简单的减法,但结果必须是正整数。我设法做了所有事情,但由于某种原因,答案有时是否定的,我不知道如何解决它

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));
}

}
}

最佳答案

两种可能的解决方案:只需更改总行,并添加一个条件,用较小的行减去较大的行(除非它们相同,在这种情况下您将得到 0)

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

或者只使用绝对值:

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

同时更改 printf:

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

条件只是确保较大的数字位于较小的数字之前,或者如果它们碰巧相等,则它们都被列出。

查看http://www.cafeaulait.org/course/week2/43.html以获得更彻底的解释?运算符。

关于java - 减去随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com