【问题标题】:How to print out the GCD in different format如何打印出不同格式的 GCD
【发布时间】:2016-01-30 22:46:16
【问题描述】:

我试图要求用户输入两个整数并有消息要说 ""第一个整数"和"第二个整数"的GCD是"GCD"

我的所有计算都是正确的,但它只是为所有值打印出我的 num1。

import java.util.Scanner;


public class Assignment3
{

    public static void main(String[] args)

    {

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter the first integer: ");
        int num1 = scan.nextInt();

        System.out.print("Enter the second integer: ");
        int num2 = scan.nextInt();

        while (num1 != num2)
        {
            if (num1> num2)
            num1 = num1 - num2;
            else
            num2 = num2 - num1;


            }


        System.out.println("The gcd of" + num1 + " and " + num2 + " is " + num1);

    }


}

【问题讨论】:

  • “但它只是打印出我的所有值的 num1” 为什么不呢?在循环中修改num1num2,循环的退出条件是num1 等于num2。如果要打印 num1num2 的原始值,请在循环之前打印它们,或者保存它们的副本以供以后打印。

标签: java printing while-loop greatest-common-divisor


【解决方案1】:

在您的 while 循环中,您检查是否 num1 != num2,因此当 println 被执行时,num1 将具有与 num2 相同的值。

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2019-06-21
    相关资源
    最近更新 更多