gpt4 book ai didi

java - 科拉兹序列 : Which number is the biggest?

转载 作者:行者123 更新时间:2023-11-30 02:38:50 25 4
gpt4 key购买 nike

所以我已经为 Collat​​z 序列编写了代码,但我希望能够识别并打印出序列中出现的最大数字。这是我的代码:

import java.util.Scanner;

public class CollatzSequence {
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
int n,ts = 0;

System.out.print("This is the Lothar Collatz Sequnce. Please enter the starting number.\n>");
n = keyboard.nextInt();

do {
if (n % 2 == 0) {
n = n / 2;
System.out.println(n);
}
else {
n = n*3 + 1;
System.out.println(n);
}
ts++;
}
while (n != 1);
System.out.println("Terminated after "+ts+" steps.");

}
}

最佳答案

创建一个名为max的变量。将其初始设置为等于n。在每个步骤中,检查是否 n > max,如果是,则将 max 设置为 n

关于java - 科拉兹序列 : Which number is the biggest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352388/

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