提问人:Neha M 提问时间:9/14/2023 最后编辑:Jim GarrisonNeha M 更新时间:9/14/2023 访问量:37
美元、加元、1.3 的输出错误;美元、英镑,0.71;美元、日元、109;英镑、日元、预计 155 预期 110.5 但得到 -1.0
getting wrong output for USD, CAD, 1.3; USD, GBP, 0.71; USD, JPY, 109; GBP, JPY, 155 expected Expected 110.5 but getting-1.0
问:
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
// Create a map of exchange rates
Map<String, Double> fxRates = new HashMap<>();
fxRates.put("USD, JPY", 109.0);
fxRates.put("USD, GBP", 0.71);
fxRates.put("GBP, JPY", 155.0);
fxRates.put("CAD, CNY", 5.27);
fxRates.put("CAD, KR", 921.0);
fxRates.put("USD, CAD", 1.3);
fxRates.put("CAD, JPY", 88.0);
// Read the input and calculate the maximum amount of the target currency
// that can be obtained from 1 unit of the selected currency
String line;
double maxAmount = -1.0;
while ((line = in.readLine()) != null) {
String[] currencies = line.split(";");
for (String currencyPair : currencies) {
String[] currencies = currencyPair.trim().split(",");
if (currencies.length == 2) {
String originalCurrency = currencies[0].trim();
String targetCurrency = currencies[1].trim();
double amount = calculateMaxAmount(fxRates, targetCurrency, originalCurrency, 1);
if (amount > maxAmount) {
maxAmount = amount;
}
}
}
}
// Print the maximum amount
System.out.println(maxAmount);
}
public static double calculateMaxAmount(Map<String, Double> fxRates, String originalCurrency, String targetCurrency, double amount) {
if (originalCurrency.equals(targetCurrency)) {
return amount;
}
double maxAmount = -1.0;
for (Map.Entry<String, Double> entry : fxRates.entrySet()) {
String[] currencies = entry.getKey().split(",");
String fromCurrency = currencies[0].trim();
String toCurrency = currencies[1].trim();
double rate = entry.getValue();
if (fromCurrency.equals(originalCurrency)) {
double newAmount = amount * rate;
double tempMaxAmount = calculateMaxAmount(fxRates, toCurrency, targetCurrency, newAmount);
if (tempMaxAmount > maxAmount) {
maxAmount = tempMaxAmount;
}
}
}
return maxAmount;
}
}
谁能让我知道我的代码有什么问题?
预期为 110.5,但得到 1.0。您提供的输入应该是:
答:
0赞
Reilas
9/14/2023
#1
"...谁能让我知道我的代码有什么问题?
预期为 110.5,但得到 1.0。..."
calculateMaxAmount 具有递归调用。
if (fromCurrency.equals(originalCurrency)) {
double newAmount = amount * rate;
double tempMaxAmount = calculateMaxAmount(fxRates, toCurrency, targetCurrency, newAmount);
if (tempMaxAmount > maxAmount) {
maxAmount = tempMaxAmount;
}
}
与 main 方法类似,如果值大于当前值,则只需分配一个值即可。
double newAmount = amount * rate;
if (newAmount > maxAmount) maxAmount = newAmount;
下面是一个示例输入和输出。
USD,GBP
155.0
评论