简体   繁体   English

精度损失->需要double,但是编译器需要int吗?

[英]loss of precision-->Required double but compiler required int?

I am a beginner in java and faced this error. 我是Java的初学者,因此遇到此错误。

Write a method named pay that accepts a real number for a TA's salary and an integer for the number of hours the TA worked this week, and returns how much money to pay the TA. 编写一个名为pay的方法,该方法接受TA的工资的实数,并接受TA本周工作的小时数的整数,然后返回支付TA的金额。 For example, the call pay(5.50, 6) should return 33.0. 例如,通话费用pay(5.50,6)应该返回33.0。

The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0. 在8点以上的任何小时内,TA都应该获得“加班”工资的1½正常工资,例如,通话费(4.00,11)应该返回(4.00 * 8)+(6.00 * 3)或50.0。

public double pay(double x,int y){
    int sum=0;
    double hours=8.0;
    if(y>hours){
       sum=(y-hours)*(1.5*x) + (hours*x);

    }
   return sum;
}

Error: 错误:

You have a mismatch between data types. This often occurs when you try to store a real number (double) into a variable or parameter that is an integer (int).
possible loss of precision
found   : double
required: int
       sum=(y-hours)*(1.5*x) + (hours*x);
                             ^
1 error
19 warnings

But the error is pointing at the + sign.What is wrong with it? 但是错误指向+号,这有什么问题? It says found:double. 它说发现:双。 But I want my output to be double. 但我希望我的输出翻倍。 But it said as required int. 但是它按要求说int。

Since sum is an int and you're returning sum in you're method, that's why you get an error. 由于sum是一个int并且您要在方法中返回sum ,这就是为什么会出错的原因。

public double pay(double x,int y){
    double sum=0;
    double hours=8.0;
    if(y>hours){
       sum=(y-hours)*(1.5*x) + (hours*x);

    }
   return sum;
}

For the second error, if you take a look at the class Math , pi() does not exist, you have to call the static variable of the class Math, so it should be : 对于第二个错误,如果您查看类Mathpi()不存在,则必须调用Math类的静态变量,因此它应该是:

public double area(double x){
    x=Math.PI*Math.pow(x,2);
    return x;

}

sum数据类型为int,而您的方法期望返回的数据类型为double。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM