[英]Having trouble with a while loop that gets a certain series of numbers from an input
我試圖將輸入的一半減半,如果%12 == 0,但如果不是,則將其乘以3,然后將1加到總和上。
我正在解決的問題是: http : //i.imgur.com/VzuPtZJ.png
使用我當前擁有的代碼(在下面),如果我輸入12,就像我從6開始的問題一樣,但是結果開始出錯,然后錯誤地出現錯誤,結果是數百萬和負數百萬等。
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
問題是如果數字為偶數,請除以2。 但是,只有在可將其除以12時,才將其除以2。
更改此行
(x % 12 == 0)
至
(x % 2 == 0)
並將while (x >= 1)
更改為while (x > 1)
這是您要查找的代碼:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.