I have some code here:
int mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
This code gives an error on both samples of returning a value saying "Type mismatch: Cannot convert from float to int." What is wrong with my code?
Thanks in advance.
-
You should get into the habit of researching your problem. Googling your error message would have given you a ton of results explaining what's going on.Kevin Workman– Kevin Workman2017年07月28日 16:46:46 +00:00Commented Jul 28, 2017 at 16:46
2 Answers 2
You need to change the return type to float in order to return decimal values (if that's what you are interested in):
float mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
Comments
First off, remember what int and float are:
intcan only hold whole numbers without decimal places, like1,42, and-54321.floatcan hold numbers with decimal places, like0.25,1.9999, and-543.21.
So, you need to figure out what you meant to return from your function: should it be an int or a float value? If it's supposed to be a float value, then you can simply change the return type of the function to float. If you want it to return an int value, then you'll have to rethink the logic inside your function so it's using int values instead.
Note that you can convert from a float to an int using the int() function. More info can be found in the reference.