gpt4 book ai didi

java - 我需要帮助来编写一段代码,找出一个序列中两个整数之间的最大差异

转载 作者:行者123 更新时间:2023-11-29 04:17:35 24 4
gpt4 key购买 nike

我需要编写一段代码,找出序列中两个整数之间的最大差异。用户应该输入连续 10 天的股票价格,程序会告诉您最大的每日变化。不过我卡住了。

import java.util.Scanner;

public class Change {

public static void main (String [] args) {
final int days = 10;
int largeDiff = 0; // largest difference
Scanner sc = new Scanner(System.in);
System.out.println("Enter a stock price:");

int price1 = sc.nextInt();

int price2 = sc.nextInt();

int diff1 = price1 - price2;

for (int i = 1; i <= 8; i++) {
int priceA = sc.nextInt();
int priceB = sc.nextInt();

int diff2 = priceA - priceB;

if (diff2 > diff1) {
diff2 = largeDiff;
}
else {
diff2 = diff1;
}

}

System.out.println(largeDiff);

}

}

最佳答案

您正在将 largeDiff 分配给 diff2。修改您的代码如下:

if (diff2 > diff1) {
largeDiff = diff2;
}
else {
largeDiff = diff1;
}

你的代码也有问题。找出最大的差异:

编辑:做以下修改:

public static void main(String[] args) {
final int days = 10;
int largeDiff = 0; // largest difference
Scanner sc = new Scanner(System.in);
System.out.println("Enter a stock price:");

int price1 = sc.nextInt();

int price2 = sc.nextInt();

int diff1 = price1 - price2;
largeDiff = Math.abs(diff1);

for (int i = 1; i <= 8; i++) {
int priceA = sc.nextInt();
int priceB = sc.nextInt();

int diff2 = Math.abs(priceA - priceB);

if (diff2 > largeDiff) {
largeDiff = diff2;
}
}

System.out.println(largeDiff);

}

注意: Math::abs 用于求绝对值

关于java - 我需要帮助来编写一段代码,找出一个序列中两个整数之间的最大差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51345188/

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