gpt4 book ai didi

没有列表数组或任何数据结构的Java冰雹序列

转载 作者:行者123 更新时间:2023-12-01 11:10:46 24 4
gpt4 key购买 nike

我正在学习java。我怀疑我的compute_Hailstone_Sequence方法在命中return语句后终止。使用 begin_num = 7steps = 10 两个输入,我的理想输出应该表示 7 22 11 34 17 52 26 13 40 20 我也怀疑我还没有增加 x 因为我的代码确实产生了前两个值 7 22 ..我不确定它是否可以产生累积算法。我知道使用数据结构的答案,但我尝试在不使用列表或数组或任何其他数据结构的情况下对其进行编码。这不是家庭作业。

import java.util.Scanner;

/**
* Created on 9/5/15.
* Following Reges, Stuart, and Martin Stepp. Building Java Programs: A Back to Basics Approach. 3rd Edition.
* Chapter 4
*/

public class Ch4 {
public static void main(String[] args) {
hailstone_Sequence();
}

public static void hailstone_Sequence(){
giveIntro();
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
// System.out.println("Please provide an ending integer: ");
// int ENDVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}

public static int compute_Hailstone_Sequence(int begin_num, int steps){
System.out.print(begin_num + " ");
for (int i = 1; i <= steps; i++ ){
int x;
if ((begin_num & 1) == 0 ){
// even
// int x = 0;
x = (begin_num / 2);
System.out.print(x + " ");
// return x;
}
else {
// int x = 0;
x = (3 * begin_num + 1);
System.out.print(x + " ");
// return x;
}
return x;
}
return begin_num;
}
}

最佳答案

试试这个,我不知道这是否是你正在寻找的,我是基于你的输出。

public static void hailstone_Sequence(){
Scanner user_console = new Scanner(System.in);
System.out.println("Please provide a starting integer: ");
int BEGINVALUE = user_console.nextInt();
System.out.println("Thank you. How long would you liked the sequence to be?");
int STEPS = user_console.nextInt();
System.out.println("Calculating..");
compute_Hailstone_Sequence(BEGINVALUE, STEPS);
}

public static void compute_Hailstone_Sequence(int begin_num, int steps){
System.out.print(begin_num + " ");
for (int i = 1; i < steps; i++ ){
if (begin_num%2 == 0 ){
begin_num = (begin_num / 2);
System.out.print(begin_num + " ");
}
else {
begin_num = (3 * begin_num) + 1;
System.out.print(begin_num + " ");
}
}
}

输出是:

Please provide a starting integer:

7

Thank you. How long would you liked the sequence to be?

10

Calculating..

7 22 11 34 17 52 26 13 40 20

关于没有列表数组或任何数据结构的Java冰雹序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418239/

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