我的新问题是myMin等于数字相等而不是实际最小值之前的最后距离。例如说我输入的前两个数字是1和2,接下来是1和3,然后是1和1.这就是说我的最小值是2.0。这就是我应该为作业获得的。
输入数字1:9
输入数字2:1
输入数字1:7
输入数字2:2
输入数字1:4
输入数字2:4
最小距离为:5.0。
输入数字1:20
输入数字2:3
输入数字1:23
输入数字2:23
5.0 + 17.0 = 22.0
我的代码:
double myMin = Double.MAX_VALUE;
double Min1,Min2;
while ( !(num1==num2) ) {
pairsMin( num1, num2, myMin);
Min1 = pairsMin( num1, num2, myMin);
System.out.print("Enter number 1: ");
num1 = in.nextDouble();
System.out.print("Enter number 2: ");
num2 = in.nextDouble();
if (num1==num2) {
System.out.print("\nThe minimum distance is: " + Min1 + "\n\n");
myMin = Double.MAX_VALUE;
System.out.print("Enter number 1: ");
num1 = in.nextDouble();
System.out.print("Enter number 2: ");
num2 = in.nextDouble();
while ( !(num1==num2)) {
pairsMin( num1, num2, myMin);
Min2 = pairsMin(num1,num2,myMin);
System.out.print("Enter number 1: ");
num1 = in.nextDouble();
System.out.print("Enter number 2: ");
num2 = in.nextDouble();
if(num1==num2) {
double totMin = Min1+Min2;
System.out.print("\n" + Min1 + " + " + Min2 + " = " + totMin + "\n");
}
}
}
} // end while loop
} // end main method
public static double pairsMin( double num1, double num2, double myMin){
double dist = Math.abs(num1-num2);
if ( dist<myMin) { // if dist is smaller than the minimum, then dist will be the new minimum
myMin = dist;
}
return myMin;
}
}
答案 0 :(得分:0)
更改两行
pairsMin( num1, num2, myMin);
到
myMin = pairsMin( num1, num2, myMin);
目前,您始终与Double.MAX_VALUE
进行比较,而不是与新的最低值进行比较。