gpt4 book ai didi

java - 从返回方法获取正确的打印输出

转载 作者:行者123 更新时间:2023-12-01 13:34:56 25 4
gpt4 key购买 nike

我正在尝试编写一小段代码,在给定 r 和 h 时输出三个数字的最小值、三个数字的最大值以及圆柱体的表面积。

我已经编写了代码,编译了它,它完全按照我想要的方式工作。然而,对于实际的打印输出,我希望它更好一点。我在这方面遇到了麻烦。

查看下面的代码,当前输出如下:356.8半径为 3.0、高为 4.5 的圆柱体的表面积为 141.3716694115407

我想在圆柱体方法之后对实际打印输出进行建模(即“5、7和3的最小值是3”和“......的最大值”)。对于圆柱体部分来说很容易,因为我的打印语句在方法中......方法本身不是返回类型。

但是 findMin 和 findMax 方法是返回类型,任何人都可以向我提供有关如何让代码实际输出不仅仅是最小值或最大值的建议或提示吗?我尝试在 main 方法下的实际 println 语句中进行实际操作,但不断出现错误。

非常感谢...来自初学者

public class Test {

public static void main(String[] args) {
System.out.println(findMin(5, 7, 3));
System.out.println(findMax(-5.1, 32.5, 56.8));
cylinderSurfaceArea(3.0, 4.5);
}

public static int findMin(int a, int b, int c) {
int minimum = Math.min(a, b);
int minimum2 = Math.min(minimum, c);
return minimum2;
}

public static double findMax(double a, double b, double c) {
double maximum = Math.max(a, b);
double maximum2 = Math.max(maximum, c);
return maximum2;
}

public static void cylinderSurfaceArea(double a, double b) {
double answer = 2 * Math.PI * (a * a) + 2 * Math.PI * a * b;
System.out.println("The surface area of a cylinder with radius " + a + " and height " + b + " is " + answer);
}

}

最佳答案

一种方法是将 print 语句放在方法中(我不推荐):

public static int findMin(int a, int b, int c)
{
int minimum = Math.min(a, b);
int minimum2 = Math.min(minimum, c);
System.out.println("The minimum of " + a + ", " + b + " and " + c + " is " + minimum2);
return minimum2;
}

另一个是存储您要找到的最小值的变量:

int a = 5, b = 7, c = 3;

并在 main() 方法中有一个 print 语句:

System.out.println("The minimum of " + a + ", " + b + " and " + c + " is " + 

注意:

您可能会发现有趣的printf,它可以以更灵活的方式使用:

System.out.printf("The minimum of %d, %d and %d is %d.", a, b, c, minimum2);
System.out.printf("The minimum of %d, %d and %d is %d.", a, b, c, findMin(5, 7, 3));

关于java - 从返回方法获取正确的打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358221/

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