Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Silly question - multiplying integers

Discussion in 'Scripting' started by Rajmahal, Jun 6, 2014.

  1. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Hi,

    This is a very nooob question ... and one I'm a little embarrassed to ask since I've been writing code for a few years now. When multiplying an int, it turns the result into a double. However, typecasting back into an int doesn't seem to work. Why is that the case?

    For example:

    int score = 5;

    score = (int) score * 1.5;

    The above code still returns score as a double. How can I multiply an integer by a value and then convert it back to an integer (rounding up / down ... don't really care)?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Code (csharp):
    1.  
    2. score = (int)(score * 1.5);
    3.  
     
    Rajmahal likes this.
  3. raycosantana

    raycosantana

    Joined:
    Dec 23, 2012
    Posts:
    319
    Last edited: Jun 6, 2014
    Rajmahal likes this.
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
  5. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Your result is a double because you are multiplying an integer with a double. C# will automatically convert ints to floats to doubles, but the other way around requires an explicit cast.

    Remember the order of operations from algebra? C# has something similar. You can see that your cast to int is occurring *before* the multiplication.
    http://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx

    In your original example score = (int) score * 1.5; this is what is happening.
    1. Cast int to an int. (No effect)
    2. Cast int to double in preparation for multiplication
    3. Multiply two doubles
    4. Assign that double result to score, which should result in an error since doubles will not automatically get cast to ints.
     
    Rajmahal likes this.
  6. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Got it .... thanks for the help! Really appreciate it.
     
  7. raycosantana

    raycosantana

    Joined:
    Dec 23, 2012
    Posts:
    319
    The CeilToInt script reference page is a copy and paste of page Ceil, the same with FloorToInt, I knew more or less how it was because of their name "Ceil-To-int", but you know names can be deceiving some times...
     
  8. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    The method signature at the top of the page says static int RoundToInt(float f)