Programming Error: Cannot implicitly convert type `float’ to `int’.

error CS0266: Cannot implicitly convert type `float' to `int'. An explicit conversion exists (are you missing a cast?)

Explanation:
This often happens when ints are used in an equation that would yield a non-int, such as a decimal (float). In the example, 100/3 is 33.33333, which is being stored in an int. An int cannot store decimals, you need a float or double for that.

Example:
int var = 100/3;

Solution:

Either change the int to a float or double, or cast your value as an int which will truncate the remainder.

Example:
int var = (int)(100/3);
or
float var = 100/3;

Advertisements

2 Comments

  1. phoxis said,

    August 24, 2011 at 11:36 pm

    In which language ? in C/C++ it is completely legal, and the division which occurs will be integer division, truncating the fractional part. doing float var = 100/3 will also get the same answer as the division performed is integer division.

  2. MandiSmash said,

    August 30, 2011 at 6:55 am

    Sorry about that — I should have mentioned that it’s for C# specifically for Unity3D programming using MonoDevelop. You are definitely correct about C++, that is how I discovered this error — I figured it would be legal, but it threw the error so I had to work around that. I’ll add languages to the post tags to clarify. Thanks for your comment!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: