Java 程序:使用递归求两个数乘积
在本教程中,我们将学习如何使用递归函数找到两个数字的乘积。递归函数是调用自身的函数。但是在继续之前,如果你不熟悉 java 中嵌套 if 语句的概念,那么一定要查看主题为【Java 中的 T0】条件语句的文章。
输入:输入数字:7
输入数字:4
输出:两个数的乘积是 28。
上述情况有两种情况:
情况 1:当值被预定义时
情况 2:当值由用户定义时
让我们看一下如何用递归函数求两个数的乘积的例子。
程序 1:用递归求两个数的乘积
在这个程序中,我们将看到如何使用带有预定义值的递归来找到两个数字的乘积。
算法:
- 开始
- 声明两个变量。
- 要求用户初始化这些变量。
- 调用递归函数求这两个数的乘积。
- 如果第一个数字小于第二个数字,则交换这些值。
- 递归求第二个数乘以第一个数的和。
- 如果其中任何一个变为零,则返回零。
- 显示结果。
- 停下来。
下面的例子演示了如何用递归求两个数的乘积。
//Java Program to Find the Product of Two Numbers Using Recursion
import java.io.*;
import java.util.*;
public class Main
{
// recursive function to calculate the product of two numbers
static int findProduct(int num1, int num2)
{
// if x is less than y then swap the numbers
if (num1 < num2)
return findProduct(num2, num1);
// iteratively calculate y times sum of x
else if (num2 != 0)
return (num1 + findProduct(num1, num2 - 1));
// if any of the two numbers is zero return zero
else
return 0;
}
// Driver Code
public static void main (String[] args)
{
int num1 = 7;
System.out.println("The first entered number is: "+num1);
int num2 = 8;
System.out.println("The second entered number is: "+num2);
System.out.print("The product of the two numbers is ");
System.out.println(findProduct(num1, num2));
}
}
第一个输入的数字是:7 第二个输入的数字是:8 两个数字的乘积是 56
程序 2:用递归求两个数的乘积
在这个程序中,我们将看到如何使用带有用户定义值的递归来找到两个数字的乘积。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明两个变量。
- 要求用户初始化这些变量。
- 调用递归函数求这两个数的乘积。
- 如果第一个数字小于第二个数字,则交换这些值。
- 递归求第二个数乘以第一个数的和。
- 如果两个数都小于 0,则返回它们绝对值的乘积。
- 如果其中任何一个变为零,则返回零。
- 显示结果。
- 停下来。
下面的例子演示了如何用递归求两个数的乘积。
//Java Program to Find the Product of Two Numbers Using Recursion
import java.util.*;
public class Main
{
// recursive function to calculate the product of two numbers
static int findProduct(int num1, int num2)
{
if (num1 > 0 && num2 < 0)
{
return findProduct(num2, num1);
}
// case 2 : both num1 and num2 are less than 0
// return the product of their absolute values
else if (num1 < 0 && num2 < 0)
{
return findProduct((-1 * num1), (-1 * num2));
}
// if num1 > num2 , swap num1 and num2
if (num1 > num2)
{
return findProduct(num2, num1);
}
else if (num2 != 0)
{
return num1 + findProduct(num1, num2 - 1);
}
// num1=0 then return 0
else
{
return 0;
}
}
// Driver Code
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number");
int num1 = sc.nextInt();
System.out.println("Enter the second number");
int num2 = sc.nextInt();
System.out.print("The product of the two numbers is ");
System.out.println(findProduct(num1, num2));
}
}
输入第一个数字:4 输入第二个数字:-5 两个数字的乘积是-20