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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

division

Discussion in 'Editor & General Support' started by yellowlabrador, Sep 10, 2007.

  1. yellowlabrador

    yellowlabrador

    Joined:
    Oct 20, 2005
    Posts:
    562
    Hi All,

    sorry for a very stoopid newb question here.

    I have this script that will simply calculate the percentage.
    somehow it just doesn't work I always get a 0. The only time it will work is if the dividend is equal the divisor.

    I tried addition, subtraction and multiplication and works just fine, tried playing with the parenthesis too.

    Just can't get the division though. :-(

    Here's the script
    Code (csharp):
    1.  
    2. var pointsEarned  = 0;
    3. var wrongAnswer  = 0;
    4. var rating  = 0.0;
    5.  
    6. var pointsEarnedResultGUI : GUIText;
    7. var wrongAnwserResultGUI : GUIText;
    8.  
    9.  
    10. function Update ()
    11. {
    12.     if(pointsEarned != 0)
    13.     {
    14.         rating = ((pointsEarned / 195)* (100));
    15.         guiText.text = rating.ToString() +("%");
    16.     }
    17. }
    18.  
    Thanks,
    Ray
     
  2. forestjohnson

    forestjohnson

    Joined:
    Oct 1, 2005
    Posts:
    1,370
    You need to cast as floats.

    With points earned = 0; (points earned / 195) is going to return an integer.

    Use points earned = 0.00; (points earned / 195.00) instead.
     
  3. yellowlabrador

    yellowlabrador

    Joined:
    Oct 20, 2005
    Posts:
    562
    Sweet,
    Thanks Forrest.

    feels good to understand what I'm trying to do.

    I thought that by making the var rating a float will make the result a float.

    :D

    Ray
     
  4. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    Well, I think it does... The problem is that the right side of the equation is performed (integer divided by an integer, resulting in an integer value of 0), then the result of that operation is cast in the data type of float (0 becomes 0.0).
     
  5. yellowlabrador

    yellowlabrador

    Joined:
    Oct 20, 2005
    Posts:
    562
    I'm learning and understanding more about programming using unity and reading the community forum and asking question here. :D

    thanks, really apppreciate it

    Ray