在 Java 中查找不同数据类型的 3 个数字中的最大值

发布于 2024-10-17 10:31:08 字数 352 浏览 6 评论 0原文

假设我有以下三个常量:

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

我想获取其中的三个并使用 Math.max() 来查找这三个常量的最大值,但是如果我传入两个以上的值,那么它会给我一个错误。例如:

// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);

请让我知道我做错了什么。

Say I have the following three constants:

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:

// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);

Please let me know what I'm doing wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

情深缘浅 2024-10-24 10:31:08

Math.max 仅接受两个参数。如果您想要最多三个,请使用 Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2))

Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

英雄似剑 2024-10-24 10:31:08

你可以使用这个:

 Collections.max(Arrays.asList(1,2,3,4));

或创建一个函数

public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals)); 
}

you can use this:

 Collections.max(Arrays.asList(1,2,3,4));

or create a function

public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals)); 
}
半城柳色半声笛 2024-10-24 10:31:08

如果可能,请使用 Apache Commons Lang 中的 NumberUtils - 那里有很多很棒的实用程序。

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])

NumberUtils.max(int[])

If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])

NumberUtils.max(int[])
樱娆 2024-10-24 10:31:08

Math.max 仅接受两个参数,不多也不少。

已发布答案的另一个不同解决方案是使用 DoubleStream.of

double max = DoubleStream.of(firstValue, secondValue, thirdValue)
                         .max()
                         .getAsDouble();

Math.max only takes two arguments, no more and no less.

Another different solution to the already posted answers would be using DoubleStream.of:

double max = DoubleStream.of(firstValue, secondValue, thirdValue)
                         .max()
                         .getAsDouble();
水溶 2024-10-24 10:31:08

Java 8 方式。适用于多个参数:

Stream.of(first, second, third).max(Integer::compareTo).get()

Java 8 way. Works for multiple parameters:

Stream.of(first, second, third).max(Integer::compareTo).get()
魂归处 2024-10-24 10:31:08

在不使用第三方库、多次调用相同方法或创建数组的情况下,您可以找到任意数量的双精度数的最大值,如下所示

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

在您的示例中,可以像这样使用 max

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}

Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

In your example, max could be used like this

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
舟遥客 2024-10-24 10:31:08

我有一个很简单的想法:

int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

当然,如果你有1000个数字,它就无法使用,但如果你有3或4个,那就简单又快速。

I have a very simple idea:

int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4, it's easy and fast.

萝莉病 2024-10-24 10:31:08

如前所述,Math.max() 仅接受两个参数。它与您当前的语法不完全兼容,但您可以尝试 Collections.max()。

如果您不喜欢这样,您可以随时为其创建自己的方法...

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

这将采用任意数量的混合数字参数(整数、双精度和浮点数),但返回值是一个对象,因此您必须将其转换为整数、双精度或浮点型。

由于不存在“MY_DOUBLE2”这样的东西,它也可能会抛出错误。

Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().

If you don't like that you can always create your own method for it...

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.

It might also be throwing an error since there is no such thing as "MY_DOUBLE2".

好听的两个字的网名 2024-10-24 10:31:08
int first = 3;  
int mid = 4; 
int last = 6;

//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which  //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
int first = 3;  
int mid = 4; 
int last = 6;

//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which  //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
聚集的泪 2024-10-24 10:31:08

如果你想做一个简单的,它会像这样

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

,输出会像这样

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

参考文献 Java™ 如何编程(早期对象),第十版

if you want to do a simple, it will be like this

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

and the output will be something like this

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

References Java™ How To Program (Early Objects), Tenth Edition

落叶缤纷 2024-10-24 10:31:08

你可以这样做:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  

You can do like this:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  
冷情妓 2024-10-24 10:31:08

没有方法的简单方法

int x = 1, y = 2, z = 3;

int biggest = x;
if (y > biggest) {
    biggest = y;
}
if (z > biggest) {
    biggest = z;
}
System.out.println(biggest);
//    System.out.println(Math.max(Math.max(x,y),z));

Simple way without methods

int x = 1, y = 2, z = 3;

int biggest = x;
if (y > biggest) {
    biggest = y;
}
if (z > biggest) {
    biggest = z;
}
System.out.println(biggest);
//    System.out.println(Math.max(Math.max(x,y),z));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文