猿问

学java搞不懂y=m*x+b

创建代数导师,尝试创建随机整数来解决 y=m*x+b。搜索并发现很多用户都使用过这个方程,但没有生成一个随机问题来要求答案并检查是否正确。这是我到目前为止所写的;


import java.util.Scanner;

class AlgebraTutor {

  private static Scanner in = new Scanner(System.in);

  public static void main(String[] args) {


      for (int x = 0; x < 1; x++){

          System.out.println("X = " + ((int)(Math.random() * 200) -99));

      }    


      for (int m = 0; m < 1; m++){

          System.out.println("M = " + ((int)(Math.random() * 200) -99));

      }


      for (int b = 0; b < 1; b++){

          System.out.println("B = " + ((int)(Math.random() * 200) -99));

      }


  }

}    

我相信我在生成 -100 和 100 之间的数字的正确道路上。我只是不知道该怎么做才能将它们组合起来,以便我可以输入创建数字的答案。我最好的猜测是


System.out.print("Y = " + m * x + b);

但这并没有像我想象的那样奏效。我希望能够输入答案并让它检查真假。感谢您提供解决此问题的任何建议。


不负相思意
浏览 157回答 2
2回答

慕慕森

您需要将值存储在变量中,例如:int x = ((int)(Math.random() * 200) -99));此外,您的 for 循环是不必要的,因为它们只运行一次,因此您可以只运行程序而不是循环一次。所以最后你的代码应该是这样的:import java.util.Scanner;class AlgebraTutor {&nbsp; private static Scanner in = new Scanner(System.in);&nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; int x = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; int m = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; int b = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; System.out.println("X = " + x);&nbsp; &nbsp; &nbsp; System.out.println("M = " + m);&nbsp; &nbsp; &nbsp; System.out.println("B = " + b);&nbsp; &nbsp; &nbsp; System.out.println("Y = " + m*x+b);&nbsp; }}&nbsp; &nbsp;要让它检查答案是对还是错,您必须执行以下操作:import java.util.Scanner;class AlgebraTutor {&nbsp; private static Scanner in = new Scanner(System.in);&nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; int x = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; int m = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; int b = ((int)(Math.random() * 200) -99);&nbsp; &nbsp; &nbsp; int y = m*x+b;&nbsp; &nbsp; &nbsp; System.out.println("X = " + x);&nbsp; &nbsp; &nbsp; System.out.println("M = " + m);&nbsp; &nbsp; &nbsp; System.out.println("B = " + b);&nbsp; &nbsp; &nbsp; int INPUT = in.nextInt();&nbsp; &nbsp; &nbsp; if(INPUT == y){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("You Got It Right!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Y = " + y);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("You Got It Wrong :(");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("The Answer was: Y = " + y);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}&nbsp;

烙印99

您示例中的变量 x、m 和 b 在每个 for 循环的范围内,但}在循环之后死亡。int x = (int)(Math.random() * 200) -99); // these variables will live long enough.int m = (int)(Math.random() * 200) -99);int b = (int)(Math.random() * 200) -99);System.out.println("X = " + x);System.out.println("M = " + m);System.out.println("B = " + b);System.out.print("Y = " + m * x + b);这应该有效,但请注意,当您尝试将这些数字除以“x/b”时要小心 - 您需要强制转换为浮点数(谷歌除以整数)
随时随地看视频慕课网APP

相关分类

Java
我要回答