java如何将两组浮点值与另外两组浮点值进行比较?
我目前正在创建一个程序来比较钻石的透明度和重量。我将输入n颗钻石,找到钻石的最长子序列,它们的重量和清晰度每次都会变得更好。我正在努力的是如何比较第一颗钻石的重量和第二颗钻石的重量等等,以及比较第一颗钻石和第二颗钻石的清晰度等等。我不确定是否每次循环都能进行两次比较,或者是否必须比较每一颗钻石。任何帮助都会很好
第一个输入是测试用例的数量,下一个输入是测试用例中钻石的数量,下面是两个浮点数,分别由代表重量和清晰度的空格分隔
这是我的代码:
import java.util.Scanner;
public class Diamonds {
static int i;
static int j;
/**
* If a diamond has high weight but low clarity, it will be worth less than a diamond with
* low weight but high clarity, what we are trying to figure out is the best sequence of diamonds
* where the value of the diamond goes up each time, we will need to compare the quality of the
* previous diamond in order to see if the next diamond is more valuable. In order to do this,
* The size needs to be bigger than the previous diamond and the clarity needs to be less than the
* previous diamond.
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Get number of test cases
int test = scan.nextInt();
// Use for loop to loop through n times until all test cases are completed
for (i = 0; i < test; i++) {
// Get number of diamonds in test case
int diamonds = scan.nextInt();
// Loop through the amount of diamonds n times until all diamonds have been compared
for (j = 0; j < diamonds; j++) {
float weight = scan.nextFloat();
float clarity = scan.nextFloat();
}
}
}
}
# 1 楼答案
首先,你必须定义钻石何时比其他钻石“更好”,理想情况下,定义一个partial order
对于您的问题,不需要(阅读时可以进行比较),但最好定义一个
Diamond
类:您可以在某个地方定义一个比较器,但通常是在类本身中
现在你可以比较
Diamond
如果你想一个接一个地阅读diamond,只得到最好的,你可以定义最差的
Diamond
(在Diamond
类上)现在,从stdin阅读,你可以初始化最好的钻石,并在阅读新钻石时变得更好
但请记住,当钻石A比钻石B更好时
旁白:有序集允许元素之间有任何可能的顺序,但通常对于数字,应该定义一个函数。体重越重越好?更清晰更好吗?一种可能的(但主观的)方法是按价格进行比较,然后你只需使用一些等式或历史或市场数据将
Diamond
转换为价格现在,您可以在
Diamond
的类中定义价格(或不是实际价格的“相对价格”)你会成为一个比较者
# 2 楼答案
一些不错的答案,但可能超出了OP的水平。下面是一个更基本的例子
想想你需要做什么。你需要阅读
n
钻石的信息。这些信息包括它们的重量和清晰度。这一部分非常简单但是,我们如何保持之前的重量和清晰度?好吧,如果这是第一次,那就不用担心了
我们需要一个地方来存储在循环迭代之间的先前信息。哦,我们可能需要当前的权重和清晰度,以便在循环迭代之间保持不变。一旦我们这样做了,如果不是第一次通过,就很容易将当前值移动到以前的值中
现在我们可以比较它们了。我们需要一个地方来储存我们的“条纹”更好的钻石。一个
int
就行了。如果当前钻石更好,我们可以增加它,如果不是,我们可以将其重置为零但这只会让我们追踪当前的连胜,而不是最长的连胜。为此,我们需要将当前条纹长度与现有最大值进行比较,并在达到新的最大值时修改最大值