Simple Typecast Q (int to float)

This is a discussion on Simple Typecast Q (int to float) within the C++ Programming forums, part of the General Programming Boards category; Is there a better way to do this...?? (the 'wins' and 'losses' variables have been previously declared as 'int') Code: ...

  1. #1
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Question Simple Typecast Q (int to float)

    Is there a better way to do this...?? (the 'wins' and 'losses' variables have been previously declared as 'int')



    Code:
    float blackjack::win_percentage()
    {
            //Prevents 'division by zero' errors
    	if ((wins + losses) == 0)
    
    		return 0.00;
    
    	else
    	{
    		
    		//Cast 'wins' & 'losses' to float 
    		cout.setf(ios::fixed);
    		cout.setf(ios::showpoint);
    		cout.precision(1);
    
    
    		float answer =  (( (float)wins / ( (float)wins + (float)losses)) * 100);
    
    		return answer;
    
    	}
    
    }

    I think there is a better way to perform this typecast.. also i think there is a different way to set precision.

    Thanks in advance.
    Last edited by The Brain; 09-01-2004 at 12:03 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,802
    Why do you even need to type cast since your declaring a float and then diving two ints in it you should still be ok without a typecast or at least i think
    Woop?

  3. #3
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Exclamation

    just tried it this way.. and the results I am getting are consistant with integer division...

    Code:
    float answer =  ((wins / (wins + losses)) * 100);
    For example, if I win the first hand.. I will get a 100% win percentage.. but if I lose the second hand.. I will have a 0% win percentage.. subsequent wins yeild 0% as anything less than 100% will truncate to zero percent.
    Last edited by The Brain; 09-01-2004 at 12:32 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Your casting is correct in your original post Mr. Brain.

  5. #5
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120
    It's correct but there is a prettier way (well less brackets anyway):


    Code:
    float answer = (float)wins / float(wins + losses) * 100;
    or, to save even more excess:


    Code:
    return (float)wins / float(wins + losses) * 100;
    There's no need for the brackets around "(float)wins / float(wins + losses)" as the divide will b done before the multiply anyway.

    As for the precision, I've no idea, but if that works I can't imagine a more efficient method.

    Hope that helps

    dt
    Last edited by DominicTrix; 09-01-2004 at 09:39 AM. Reason: another thought
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

  6. #6
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    Code:
    floatVar = static_cast<float>(intVar);
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  7. #7
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    We where discussing casts in my c/c++ class today and I made the comment that the form (type)expression for casting is the c-style form of casting and that the new style forms for c++ are prefered.

    Taken Effective C++ second edition by Scott Meyers the casts are
    static_cast<type>(expression)
    const_cast<type>(expression)
    dynamic_cast<type>(expression)
    reinterpret_cast<type>(expression)

    while this casting may be more typing as Meyers points out they are easier to identify and "the narrower focus of the casts allow compilers to diagnose usage errors"

  8. #8
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120
    Wow, so exactly why is using this style class preffered over type(expression) or (type)expression? I understand the recognition, it is very clear to read (if that's what you mean), but what you quote Meyers as saying makes no sense to me. Does what he say really apply in a case as simple as this?
    Last edited by DominicTrix; 09-01-2004 at 07:00 PM. Reason: realised an error
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

  9. #9
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    Well I admit I originaly learned to use the simple c style type casting but having read other books on the subject I think that the change in syntax does apply.
    The simplicty may not be apparent to the beginning programmer. Suppose a client misinterprets the traditional style of casting for a function call or some other anomoli. Still the static_cast<type>(expression) form leaves no room for misinterpretation or incorrect casting. Neatly formated code would make clarity a simple process. The potenitial for error would decrease because of the apparent signal for possible logic errors in incorrect type casting. This is all my opinion on the subject. I have little programming experience so take it with a grain of salt if you like but it has caused me some thought upon the subject. It is tempting to take the route that most simply leades to our destination but taking the alternate route may lead to a clearer understanding of the code across all level of programmers. I would think the experienced programmers are used to the traditional c-style casting and many would resist changing to the newer c++ style casts but who knows perhaps my own opinion could be changed with more experience or by your own replies.

  10. #10
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120
    Was just looking for Meyer's book to buy, when saw some demo snippets online, including the chapter on type casting! It's here,

    http://www.awprofessional.com/conten...MEC/MI5_FR.HTM

    I've not read it all yet, but enough to see at least one reason for using the C++ style (to do with avoiding conversions from double to char etc).
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

  11. #11
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    Lightbulb

    Aside from casting an int to a float... I have also realized a better way to write this algorithm... using an optimization method called, "stacking the deck" (no pun intended)

    Since ((wins + losses) == 0) will only occur on the opening hand.. why not make this the ELSE.

    more optimal approach
    Code:
    float blackjack::win_percentage()
    {
    
    	//Prevents division by zero error
    	if ((wins + losses) != 0)
    	{
    		
    		//Cast wins & losses to float 
    		cout.setf(ios::fixed);
    		cout.setf(ios::showpoint);
    		cout.precision(1);
    
    		float answer =  (( (float)wins / ( (float)wins + (float)losses)) * 100);
    
    		return answer;
    
    	}
    
    	else
    
    	        return 0.00;
    
    }
    With this type of architecture, the IF statement should only short circuit on the opening hand... all subsquent hands will satisfy ((wins + losses) != 0)... thus, "stacking the deck" towards the more frequently satisfied condition... saving a ton of overhead by not having to resort to ELSE everytime.

    simple yet fun technique.
    Last edited by The Brain; 09-01-2004 at 10:19 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  12. #12
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Just want to let everyone know.. that I have settled on this hybrid approach to making this typecast...


    Code:
    float blackjack::win_percentage()
    {
    
    	//Prevents division by zero error
    	if ((wins + losses) != 0)
    	{			
    		cout.setf(ios::fixed);
    		cout.setf(ios::showpoint);
    		cout.precision(1);
    
    		//Typecast wins & losses to float 
    		float answer = static_cast<float>((wins) / ( wins + (float)losses)) * 100;
    
    		return answer;
    	}
    
    
    	else
    
    		return 0.00;
    
    }
    Last edited by The Brain; 09-11-2004 at 12:29 AM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  13. #13
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >also i think there is a different way to set precision.
    I suppose you could do it like this:
    Code:
    cout << fixed << showpoint << setprecision(1);

  14. #14
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120
    If your going to use the hybrid (and I'm not sure why you would), then why not use the yet again more efficient:

    Code:
     return   static_cast<float>(wins) / (float)(wins + losses) * 100;
    That way, there is no need to setup the extraneous float variable and you ditch a set of brackets that you didn't need (the devide will be done before the multiplication anyway).

    I think though, that for total clarity and consistency, you should use one type of cast. i.e.:

    Code:
          return   static_cast<float>(wins) / static_cast<float>(wins + losses) * 100.0;
    
    // or
    
          return float(wins) / float(wins + losses) * 100.0;
    dt
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

  15. #15
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,662
    I wouldn't modify cout's flags unless you're actually going to use it. You may also want to consider restoring cout's original flags once you've done your output, to "play nice" with any other output functions that you add later which can expect the default flags to be set.

    As for the casting, in this case you only need one cast to promote the entire expression to float:
    >> ((float)wins / (wins + losses)) * 100

    >> saving a ton of overhead
    There's extremely little "overhead" in a single jump instruction, not a ton. You can also perform "wins + losses" calculation once and don't touch cout.
    Code:
    float blackjack::win_percentage()
    {
        int tot = wins + losses;
    
        if (tot)
            return ((float)wins / tot) * 100;
    
        return 0;
    }//win_percentage
    gg

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 07:19 AM
  2. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  3. Moving Average Question
    By GCNDoug in forum C Programming
    Replies: 4
    Last Post: 04-23-2007, 11:05 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21