java 不兼容的类型:从 double 到 int 的可能有损转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29173575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incompatible types: possible lossy conversion from double to int
提问by Sublīmis
Help? I don't know why I am getting this error. I am getting at in line 39:
帮助?我不知道为什么我会收到此错误。我在第 39 行:
term[1] = differentiate(Coeff[1], exponent[1]);
How can I fix this issue?
我该如何解决这个问题?
Full code listing:
完整代码清单:
public class Calcprog {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTerms = 7;
double[] Coeff = new double[6];
double[] exponent = new double[6];
String[] term = new String[6];
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
while (numTerms > 6) {
if (numTerms > 6) {
System.out.println("Please limit the number of terms to six.");
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
}
}
for (int i = 1; i < numTerms + 1; i++) {
System.out.println("Please enter the coefficient of term #" + i + " in decimal form:");
Coeff[i] = input.nextDouble();
System.out.println("Please enter the exponent of term #" + i + " in decimal form:");
exponent[i] = input.nextDouble();
}
term[1] = differentiate(Coeff[1], exponent[1]);
}
public String differentiate(int co, int exp) {
double newco, newexp;
String derivative;
newexp = exp - 1;
newco = co * exp;
derivative = Double.toString(newco) + "x" + Double.toString(newexp);
return derivative;
}
}
回答by Eran
You are trying to pass double arguments to a method that accepts ints, which requires a casting that may result in loss of information.
您正在尝试将双参数传递给接受整数的方法,这需要可能导致信息丢失的强制转换。
You can make it work by an explicit cast :
您可以通过显式转换使其工作:
term[1] = differentiate((int)Coeff[1], (int)exponent[1]);
Or you can change your differentiate
method to accept double arguments, which would probably make more sense :
或者您可以更改您的differentiate
方法以接受双参数,这可能更有意义:
public String differentiate(double co, double exp)
回答by Rafael Reis
your method is not static, and you calling in the main which is static, remember a non static method can be access direct in a static method, you have to create an instance of the class to access that method, and also the parameter you are passing is double
and not int
. Your method should be like that public static String differentiate(double co, double exp){
你的方法不是静态的,你调用的是静态的 main,记住一个非静态方法可以直接在静态方法中访问,你必须创建一个类的实例来访问该方法,以及你的参数路过是double
与不是int
。你的方法应该是这样的public static String differentiate(double co, double exp){
回答by René Winkler
change the argument types of the differentiate method to double. This should then look as follows
将差异方法的参数类型更改为双精度。这应该如下所示
public String differentiate(double co, double exp){
...
}