gpt4 book ai didi

java - 我需要帮助打印出程序中出现的最大绝对差异的价格。 (我快完成了。)

转载 作者:行者123 更新时间:2023-12-02 11:00:42 25 4
gpt4 key购买 nike

我无法找出在 if 条件下更新价格的正确方法。这可能真的很简单,但我遇到了麻烦。这是我的代码。

public class Change {
public static void main(String[] args) {
final int days = 10;
int largeDiff = 0; // largest difference
int price2 = 0;
int day1 = 1;
int day2 = 2;

Scanner sc = new Scanner(System.in);
System.out.println("Enter stock prices:");

int price1 = sc.nextInt();

for (int i = 2; i <= days; i++) {
price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
price1 = price2;

if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
}
}

System.out.println("Largest change of " + largeDiff);
System.out.println("from " + price1 + " to " + price2);
System.out.println("happened between day " + day1 + " and day " + day2);
}
}

最佳答案

你的问题是线路

System.out.println("from " + price1 + " to " + price2);

因为在循环结束时,price1price2 都将是最后输入的价格。

您需要做的是,当您存储 largeDiffday1day2 的值时,您还应该存储这两个价格的值。然后在循环结束时,打印这些存储的值,而不是 price1price2

price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
storedPrice1 = price1;
storedPrice2 = price2;
}
price1 = price2;

}

System.out.println("Largest change of " + largeDiff);
System.out.println("from " + storedPrice1 + " to " + storedPrice2);

关于java - 我需要帮助打印出程序中出现的最大绝对差异的价格。 (我快完成了。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352071/

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