在递归方法中将 int 和 double 相乘
multiplying int and double in recursive method
在下面的程序中,用户输入 a
表示他们工作了多少小时,b
表示他们的时薪,然后计算他们的工资。
当 a
和 b
都是类型 int
时,它正在工作,然后我意识到我的老师要求 b
是双打。
我尝试将 b
的所有内容从 int
更改为 double
,但现在返回错误。
我做错了什么?
import java.util.Scanner;
public class Project61 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the amount of hours first and then the hourly rate");
int a=in.nextInt();
double b=in.nextDouble();
double res = mult (a, b);
System.out.println("Hours : "+ a);
System.out.println("Rate per hour : "+ "$"+ b);
System.out.println("Pay : "+ "$" +res);
}
public static double mult(int a, double b) {
if(b ==1){
return a;
}
if (b<1) {
return -a + mult(a, b+1);
}
else{
return a + mult(a, b-1);
}
}
}
问题是,如果 b
不等于整数(例如,如果 b == 2.5
),你将 永远不会 得到 1反复从中减去 1。因此,您的递归函数将使用 b == 1.5
调用自身,然后使用 b == 0.5
,然后再次使用 b == 1.5
,无穷无尽(或者至少,ad untilum Javaum runsum outum ofum stackum memoryum)。您需要创建一个可以保证最终会被触发的退出案例。
您必须将 int a 转换为 double。您不能将 double 与整数相乘。您可以在输入后或仅在
中将 int a 转换为 double
method public static double mult(int a, double b)
{
double aa = a.doubleValue();
if(b ==1)
{
return a;
}
if (b<1)
{
return -aa + mult(aa, b+1);
}
else
{
return aa + mult(aa, b-1);
}
}
在下面的程序中,用户输入 a
表示他们工作了多少小时,b
表示他们的时薪,然后计算他们的工资。
当 a
和 b
都是类型 int
时,它正在工作,然后我意识到我的老师要求 b
是双打。
我尝试将 b
的所有内容从 int
更改为 double
,但现在返回错误。
我做错了什么?
import java.util.Scanner;
public class Project61 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the amount of hours first and then the hourly rate");
int a=in.nextInt();
double b=in.nextDouble();
double res = mult (a, b);
System.out.println("Hours : "+ a);
System.out.println("Rate per hour : "+ "$"+ b);
System.out.println("Pay : "+ "$" +res);
}
public static double mult(int a, double b) {
if(b ==1){
return a;
}
if (b<1) {
return -a + mult(a, b+1);
}
else{
return a + mult(a, b-1);
}
}
}
问题是,如果 b
不等于整数(例如,如果 b == 2.5
),你将 永远不会 得到 1反复从中减去 1。因此,您的递归函数将使用 b == 1.5
调用自身,然后使用 b == 0.5
,然后再次使用 b == 1.5
,无穷无尽(或者至少,ad untilum Javaum runsum outum ofum stackum memoryum)。您需要创建一个可以保证最终会被触发的退出案例。
您必须将 int a 转换为 double。您不能将 double 与整数相乘。您可以在输入后或仅在
中将 int a 转换为 doublemethod public static double mult(int a, double b)
{
double aa = a.doubleValue();
if(b ==1)
{
return a;
}
if (b<1)
{
return -aa + mult(aa, b+1);
}
else
{
return aa + mult(aa, b-1);
}
}