无法从 float 转换为 int Processing/Java
Cannot convert from float to int Processing/Java
我这里有一些代码:
int mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
这段代码在返回值的两个样本上都给出了一个错误,说 "Type mismatch: Cannot convert from float to int." 我的代码有什么问题?
提前致谢。
您需要将 return 类型更改为 float 以便 return 十进制值(如果您对此感兴趣):
float mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
首先,记住 int
和 float
是什么:
int
只能容纳不带小数位的整数,例如 1
、42
和 -54321
.
float
可以保存带小数位的数字,例如 0.25
、1.9999
和 -543.21
.
因此,您需要从函数中弄清楚 return 的含义:它应该是 int
还是 float
值?如果它应该是一个 float
值,那么您只需将函数的 return 类型更改为 float
。如果您希望它成为 return 一个 int
值,那么您将不得不重新考虑函数内部的逻辑,因此它使用 int
值。
请注意,您可以使用 int()
函数将 float
转换为 int
。可以在 the reference.
中找到更多信息
我这里有一些代码:
int mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
这段代码在返回值的两个样本上都给出了一个错误,说 "Type mismatch: Cannot convert from float to int." 我的代码有什么问题?
提前致谢。
您需要将 return 类型更改为 float 以便 return 十进制值(如果您对此感兴趣):
float mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
首先,记住 int
和 float
是什么:
int
只能容纳不带小数位的整数,例如1
、42
和-54321
.float
可以保存带小数位的数字,例如0.25
、1.9999
和-543.21
.
因此,您需要从函数中弄清楚 return 的含义:它应该是 int
还是 float
值?如果它应该是一个 float
值,那么您只需将函数的 return 类型更改为 float
。如果您希望它成为 return 一个 int
值,那么您将不得不重新考虑函数内部的逻辑,因此它使用 int
值。
请注意,您可以使用 int()
函数将 float
转换为 int
。可以在 the reference.