user8215383
user8215383

Reputation:

Cannot convert from float to int Processing/Java

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.

Upvotes: 0

Views: 5738

Answers (2)

Kevin Workman
Kevin Workman

Reputation: 42174

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.

Upvotes: 3

Yuval Ben-Arie
Yuval Ben-Arie

Reputation: 1290

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; 
    }
}

Upvotes: 3

Related Questions