我想写一个数字,然后做一个操作(如果 N 是偶数,那么 N/2,或者如果 N 是奇数,那么 (N*3) +1)并一直做直



我想制作一个算法,它可以接受我写的一个数字,然后做一个操作,然后取答案,并重复新数字,直到数字等于 1

import java.util.Scanner;
public class Nombres {
   public static void main(String args[]) {
      int amount;
      Scanner keyboard = new Scanner(System.in);
      System.out.print("Inscrivez un nombre");
      amount = keyboard.nextInt();
      while (amount != 1) {
         if (amount % 2 > 0) {
            System.out.println((amount * 3) + 1);
         }
         if (amount % 2 == 0) {
            System.out.println(amount / 2);
         }
         if (amount == 1) {
            System.out.println("FIN");
         }
      }
      if (amount == 1) {
         System.out.println("1 FIN");
      }
   }
}

您不会更改每个迭代的amount。 例如

if (amount % 2 == 0)
    amount = amount / 2;
else
    amount = amount * 3 + 1
System.out.println(amount);

相关内容

最新更新