[英]multiplying int and double in recursive method
In the following program, the user enters a
for how many hours they've worked, and b
for their hourly rate, then it calculates their pay.在下面的程序中,用户输入
a
表示他们工作了多少小时,输入b
表示他们的小时费率,然后计算他们的工资。
It was working when both a
and b
were type int
, then I realized my teacher asked for b
to be a double.当
a
和b
都是int
类型时它正在工作,然后我意识到我的老师要求b
是双精度型。
I tried changing everything for b
from int
to double
, but now it is returning an error.我尝试将
b
所有内容从int
更改为double
,但现在它返回错误。
What am I doing wrong?我究竟做错了什么?
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);
}
}
}
The problem is that, if b
is not equal to an integer (for instance, if b == 2.5
), you will never get 1 by repeatedly subtracting 1 from it.问题是,如果
b
不等于一个整数(例如,如果b == 2.5
),你将永远不会通过重复减去 1 得到 1。 So your recursive function will call itself with b == 1.5
, then with b == 0.5
, then again with b == 1.5
, ad infinitum (or at least, ad untilum Javaum runsum outum ofum stackum memoryum).因此,您的递归函数将使用
b == 1.5
调用自身,然后使用b == 0.5
,然后再次使用b == 1.5
,无限期(或至少, ad untilum Javaum runsum outum ofum stackum memoryum)。 You need to create an exit case that you can guarantee will be triggered eventually.您需要创建一个可以保证最终会触发的退出案例。
You have to convert int a to double.您必须将 int a 转换为 double。 You can not multiply double with integer.
您不能将 double 与 integer 相乘。 You could convert int a to double after input or just in
您可以在输入后或仅在输入后将 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.