0

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.

Kevin Workman
42.3k12 gold badges72 silver badges110 bronze badges
asked Jul 28, 2017 at 13:06
1
  • 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. Commented Jul 28, 2017 at 16:46

2 Answers 2

3

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; 
 }
}
answered Jul 28, 2017 at 13:09
Sign up to request clarification or add additional context in comments.

Comments

3

First off, remember what int and float are:

  • int can only hold whole numbers without decimal places, like 1, 42, and -54321.
  • float can hold numbers with decimal places, like 0.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.

answered Jul 28, 2017 at 16:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.