作为问题集的一部分,我必须按升序排序3个数字.一个简单的任务,但由于某种原因,我没有得到预期的结果.不允许使用数组.以下是我的代码; 我在这里链接了我的流程图.我无法让程序对5个数字进行排序,例如5,5和-4.当我尝试这种情况时,这是输出:
Enter three numbers.
Run Code Online (Sandbox Code Playgroud)
按顺序-0.04 5.0 5.0订购5.0 -0.04 5.0
如果我让那个工作,我不能得到23,0,39的情况进行排序.不确定我是否因为这么多案件而过度复杂化; 我觉得我的流程图涵盖了所有可能性.提前致谢!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter three numbers.");
double x = reader.nextDouble();
double y = reader.nextDouble();
double z = reader.nextDouble();
if (x >= y){
if (y >= z)
System.out.print("In order " + z + " "+ y + " " + x);
if (z >= x)
System.out.print("In order " + y + " "+ x + " " + z);
if (x > z)
System.out.print("In order " + y + " " + z + " " + x);
}
if (y > x)
{
if (z >= y)
System.out.print("In order " + x + " " + y + " "+ z);
if (z >= x)
System.out.print("In order " + y + " " + x + " " + z);
if (x > z)
System.out.print("In order " + y + " " + z + " " + x);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以没有解决这个if使用(S)Math.max(double, double)和Math.min(double, double)和基本的加减.喜欢,
double max = Math.max(x, Math.max(y, z));
double min = Math.min(x, Math.min(y, z));
double mid = x + y + z - max - min;
System.out.printf("In order %f %f %f%n", min, mid, max);
Run Code Online (Sandbox Code Playgroud)
使用if和else比较,而不是Math.max和Math.min是一个比较复杂的.选择一个默认值并与其他两个进行比较.喜欢,
double max = z;
if (x > max || y > max) {
if (x > y) {
max = x;
} else {
max = y;
}
}
double min = z;
if (x < min || y < min) {
if (x < y) {
min = x;
} else {
min = y;
}
}
double mid = x + y + z - max - min;
System.out.printf("In order %f %f %f%n", min, mid, max);
Run Code Online (Sandbox Code Playgroud)