【问题标题】:Math Class, Methods, and random Numbers (Java)数学类、方法和随机数 (Java)
【发布时间】:2017-02-13 03:14:41
【问题描述】:

绝望需要帮助我完成一个 Java 程序,我需要为学校竞争!在过去的 3 天里,我已经为此工作了至少 3 个小时,但我无法弄清楚.... =(这里是方向:

编写一个程序,调用下面列表中 Math 类的每个方法,并提供显示调用的方法、发送到该方法的值以及返回的结果的输出。每个列出的方法都会告诉您要使用哪些值。例如:

列出的方法:

double pow(double a, double b): use 2.0 and 3.0.

你的程序会显示:

Math.pow(2.0, 3.0) = 8.0.

在调用接受双精度的方法时,请使用至少包含一个十进制数字的数字,如上例所示,即使它是零。请记住,带小数的数字是双重文字。尝试使用能够产生易于验证的结果的值。

这里是列表:

double pow(double a, double b): Use 3.0 and 2.0

double sqrt(double x): Use 25.0

int max(int a, int b): Use 6 and 2

double max(double a, double b): Use -50.0 and 7.0

static double random()

样本输出:

Math.pow(3.0, 2.0) = 9.0

Math.sqrt(25.0)=5.0

Math.max(6,2)=6

Math.max(-50.0,7.0)=7.0

Math.random()= /*-random value-*/

使用示例中显示的值测试您的程序,修复所有错误。 向您的程序添加一个名为 randomStudy 的方法,该方法没有参数并且不返回任何值。在此方法中,请执行以下操作:

一个。声明三个 int 变量:total、min 和 max。将总计设置为 0,最小值设置为 11,最大值设置为 -1。

b.创建一个将运行 1,000 次的循环。在循环体中,生成一个介于 1 和 10 之间的随机 int 值,包括 1 和 10。将此数字添加到您的总数中。如果此数字小于 min,则将 min 更新为新数字。如果大于 max,则将 max 更新为新数字。

c。循环结束后,显示如下:

最小值:x 最大值:y 平均:z 用您的最小值和最大值替换 x 和 y。通过将您的总数除以 1000d 来计算 z。 从 main 方法调用新的 randomStudy 方法。 突出显示并复制 Eclipse 中显示的输出。将输出粘贴到源代码文件的底部。添加文本结果:在您的输出上方,然后注释掉您刚刚添加的文本以及输出文本。您的评论结果应如下所示:

/*

Results:

Math.pow(3.0, 2.0)= 9.0

Math.sqrt(25.0) = 5.0

Math.max(6, 2) = 6

Math.max(-50.0, 7.0) = 7.0

Math.random() = -random number-

Min value: 1

Max value: 10

Average: 5.553

*/

所以,我遇到的问题是关于运行循环 1,000 次然后显示 1,000 个数字中的最大和最小数字的最后一部分。并且还显示 1,000 个数字的平均值。这是我的代码

 class MathMethodsProgram {

public static void main(String[] args) {
    //      Prints the pow method. 

    System.out.println("Math.pow(2.0, 3.0) = " + Math.pow(2.0, 3.0));

   //       Prints the sqrt method

    System.out.println("Math.sqrt(25) = " + Math.sqrt(25));

    //      Prints the max number 

    System.out.println("Math.max( 6, 3) = " + Math.max(6, 3));

   //       Prints the max number

    System.out.println("Math.max(-50.0,7.0) = " + Math.max(-50.0, 7.0));

   //       Prints a random number 
    System.out.println("Math.random(); = " + Math.random());    

    randomStudy();

    }

public static void randomStudy(){
    int total = 0; 
    int min = 11; 
    int max = -1; 
    int newtotal = 0;
    int i; 
    int randomInt = 0;

        for( i = 0; i < 1000; i++){             
             randomInt = 1 + (int)( Math.random() * 11);

             newtotal = (randomInt + total);

            }
        if (randomInt < min) {
            min = 1 + (int) Math.random();
        } else {
            System.out.println("Min: " + min);
        }

        if (randomInt > max) {
            max = 1 + (int) Math.random();
        } else {
            System.out.println("Max: " + max);
         }

         System.out.println("Min value:" + min);
         System.out.println("Max Value:" + max);
         System.out.println("Average:"+ newtotal / 1000d);
    }



}

当我在 Eclipse 中运行代码时,输​​出如下:

 Math.pow(2.0, 3.0) = 8.0
Math.sqrt(25) = 5.0
Math.max( 6, 3) = 6
Math.max(-50.0,7.0) = 7.0
Math.random(); = 0.1824716748725944
Min value:1
Max Value:1
Average:0.008

提前致谢

【问题讨论】:

  • 问题是你在检查值之前关闭循环迭代!
  • 此外,您询问if (randomValue &lt; min),然后将 new 随机值分配给 min:min = 1 + (int) Math.random();。此外,如果您只是调用Math.random(),它将生成一个介于01 之间的值。由于floatds 和doubles 在转换为int 时会被取底,因此您只会得到1 作为结果
  • 如果您注意正确格式化代码,错误可能会变得很明显!您需要在每个循环的迭代中检查并更新您的 minmax
  • 我该如何解决这些问题?我是 Java 的完全初学者。 =(
  • @BlazeRyder 如果您参加编程课程,请询问您的老师/教授,他们会得到报酬来解释事情。或者阅读教程,例如this one

标签: java random methods


【解决方案1】:

在你的 1000 个 for 循环中,你有

newtotal = (randomInt + total);

它不会增加 newtotal,它只会取最后一个数字。看起来你的最后一个数字是 8,所以平均值是 0.008。最好是:

total = (randomInt + total);
// Then after the for loop is complete, average = total / 1000;

接下来,为了比较 randomInt 与 min/max,而不是分配新的随机值,您应该根据最后一个随机数分配新的 min/max(这需要在您的 1000 for 循环内,而不是之后) :

if (randomInt > max) {
    max = randomInt;
}

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您的代码非常接近。

    你只需要把你的 if 语句放在 for 循环和你写的地方

    max = 1 + (int) Math.random();
    

    应改为:

    max = randomInt;
    

    (对 min 执行相同操作,使其显示为“min = randomInt;”)

    【讨论】:

      【解决方案3】:

      在这里,我将提供我创建的代码。我的目的是让您了解如何创建与我们从 Math 类中获得的函数等效的多个函数。我包括了帮助这些类不言自明的 cmets,我希望这对你有所帮助。我还包括显示数据的对话框,因此如果有人正在寻求如何使用 javax.swing 类的帮助,这是一个很好的资源。

      第一个类MyMath.java 包含用于执行所有计算的方法。

      package com.exercise.lecture2;
      
      /**
       * Create a class call "MyMath" that has the following class methods:
       * static boolean isEven(int x) --> returns true is number is even
       * static long absolute(long x) --> returns the absolute value of x
       * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
       * static double max (double a, double b) --> returns max of a or b
       * static double min (double a, double b ) --> returns min of a or b
       * 
       * @author Samuel
       *
       */
      public class MyMath {
      
          /**
           * An even number is an integer which is "evenly divisible" by two. 
           * This means that if the integer is divided by 2, it yields no remainder. 
           * Zero is an even number because zero divided by two equals zero, which despite not being a natural number, is an integer. 
           * Even numbers can be either positive or negative.
           * 
           * @param x
           * @return
           */
          static boolean isEven(int x){
              if (x % 2 == 0) 
                  return true;
              else
                  return false;
          }
      
          /**
           * In mathematics, the absolute value or modulus of a real number is the number without the sign. 
           * The absolute value of 2 is 2, the absolute value of -2 is also 2.
           * 
           * @param x
           * @return
           */
          static long absolute(long x) {
              if (x >= 0)
                  return x;
              else
                  return (-1*x); 
          }
      
          /**
           * The hypotenuse is the side opposite the 90 degrees angle in a right triangle. It is always the longest side.
           * 
           * @param x
           * @param y
           * @return
           */
          static double hypotenuse (double x, double y) {
              return Math.sqrt((x * x) + (y * y));
          }
      
          /**
           * Maximum of two values
           * @param a
           * @param b
           * @return
           */
          static double max (double a, double b) {
              if (a >= b)
                  return a;
              else
                  return b;       
          }
      
          /**
           * Minimum of two values
           * @param a
           * @param b
           * @return
           */
          static double min (double a, double b ) {
              if (a < b)
                  return a;
              else
                  return b;
          }   
      
      }
      

      第二个类 MathClassTest.java 包含 javax.swing 类,以便使用对话框显示。

      package com.exercise.lecture2;
      
      import javax.swing.JOptionPane; // importing the javax.swing class in order to use dialog box in my code
      
      /**
       * static boolean isEven(int x) --> returns true is number is even
       * static long absolute(long x) --> returns the absolute value of x
       * static double hypotenuse (double x, double y) --> returns sqrt(x^2 + y^2)
       * static double max (double a, double b) --> returns max of a or b
       * static double min (double a, double b ) --> returns min of a or b
       * 
       * Write an application that allows the user to select between the above methods and
       * returns the response to the user.
       * 
       * @author Samuel
       *
       */
      public class MathClassTest {
      
          public static void main(String[] args) {
      
              /* used to test the functions on MyMath.java class, here is how all of this begin
               * then I change it to make this tester use javax.swing class in order to display using 
               * dialog boxes.
               * 
               // is Even
              System.out.println(MyMath.isEven(-100));
      
              // Absolute value of an integer
              System.out.println(MyMath.absolute(-10));
      
              // Hypotenuse of two values
              System.out.println(MyMath.hypotenuse(3, 4));
      
              // Max of two values
              System.out.println(MyMath.max(3, -4));
      
              // Min of two values
              System.out.println(MyMath.min(3, -4));
      
              */
      
              boolean repeat;
              do {
                  //String name = JOptionPane.showInputDialog(null, "Enter your name", "Enter name", JOptionPane.PLAIN_MESSAGE);
                  String option = JOptionPane.showInputDialog(null,"Choose 'a' or 'A' to determine if a number is EVEN or not. \n" // options
                          + "Choose 'b' or 'B' to determine the ABSOLUTE value of a number. \n" // the (+) sign concatenate the all of the followings Strings as one
                          + "Choose 'c' or 'C' to determine the HYPOTENUSE of two values. \n"
                          + "Choose 'd' or 'D' to determine the MAXIMUM of two values. \n"
                          + "Choose 'e' or 'E' to determine the MINIMUM of two values. \n"
                          + "Choose 'q' or 'Q' to quit this simple application. \n\n" 
                          , "My Math class, by S. Mayol", JOptionPane.QUESTION_MESSAGE); // title bar of the dialog box
                  repeat = true;
      
                  if (option.equals("Q") || option.equals("q")) {
                      JOptionPane.showMessageDialog(null, "Thank you for participating...", "by Samuel Mayol", JOptionPane.INFORMATION_MESSAGE);
                      repeat = false;
                      System.exit(0);
                  } else {
                      if (option.equals("A")||option.equals("a")){
                          try { // to prevent that the value inserted is an integer and not a letter
                              String val = JOptionPane.showInputDialog("Enter a number to deternine if the number is even");
                              JOptionPane.showMessageDialog(null, "Is the number " + val + " even? " + MyMath.isEven(Integer.valueOf(val)),
                                      "Even", JOptionPane.INFORMATION_MESSAGE); // add a title message on a dialog box
                              repeat = true;
                          } catch(Exception e){
                              JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!", 
                                      JOptionPane.WARNING_MESSAGE);
                          }
                      }
                      else if (option.equals("B")||option.equals("b")){
                          try { 
                              String val = JOptionPane.showInputDialog("Enter a number to calculate absolute value of that number");
                              JOptionPane.showMessageDialog(null, "The absolute value of " + val + " is: " + MyMath.absolute(Long.valueOf(val)), 
                                      "Absolute", JOptionPane.INFORMATION_MESSAGE);
                              repeat = true;
                          } catch(Exception e){
                              JOptionPane.showMessageDialog(null, "The input " + option + " is not valid integer, please try again", "WARNING!!!", 
                                      JOptionPane.WARNING_MESSAGE);
                          }
                      }
                      else if (option.equals("C")||option.equals("c")){
                          try {
                              String val = JOptionPane.showInputDialog("Enter the first side to calculate the hypotenuse");
                              String val2 = JOptionPane.showInputDialog("Enter the second side to calculate the hypotenuse");
                              JOptionPane.showMessageDialog(null, "The hypotenuse of " + val + " and " + val2 + " is: " + MyMath.hypotenuse(Double.valueOf(val), Double.valueOf(val2)),
                                      "Hypotenuse", JOptionPane.INFORMATION_MESSAGE);
                              repeat = true;
                          } catch(Exception e){
                              JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!", 
                                      JOptionPane.WARNING_MESSAGE);
                          }
                      }
                      else if (option.equals("D")||option.equals("d")){
                          try {
                              String val = JOptionPane.showInputDialog("Enter the first number to calculate the max value");
                              String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the max value");
                              JOptionPane.showMessageDialog(null, "The max of " + val + " and " + val2 + " is: " + MyMath.max(Double.valueOf(val), Double.valueOf(val2)),
                                      "Maximum", JOptionPane.INFORMATION_MESSAGE);
                              repeat = true;
                          } catch(Exception e){
                              JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!", 
                                      JOptionPane.WARNING_MESSAGE);
                          }
                      }
                      else if (option.equals("E")||option.equals("e")){
                          try {
                              String val = JOptionPane.showInputDialog("Enter the first number to calculate the min value");
                              String val2 = JOptionPane.showInputDialog("Enter the second number to calculate the min value");
                              JOptionPane.showMessageDialog(null, "The min of " + val + " and " + val2 + " is: " + MyMath.min(Double.valueOf(val), Double.valueOf(val2)),
                                      "Minimum", JOptionPane.INFORMATION_MESSAGE);
                              repeat = true;
                          } catch(Exception e){
                              JOptionPane.showMessageDialog(null, "The any of the inputs " + option + " are not valid integer, please try again", "WARNING!!!", 
                                      JOptionPane.WARNING_MESSAGE);
                          }
                      }
                      else
                          JOptionPane.showMessageDialog(null, "The input " + option + " is not valid, please try again", "A, B, C, D, E, or Q", 
                              JOptionPane.WARNING_MESSAGE);
                  }
              } while(repeat);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        • 2015-09-23
        相关资源
        最近更新 更多