Computer Science Canada Switch Statement Help |
Author: | bfh [ Sat Jul 31, 2010 9:45 pm ] | ||
Post subject: | Switch Statement Help | ||
First ill outline the problem: the problem is that the switch statements seem to print everything... not just whats needed... Some info: using rand function to gen a random card 1-52. then wanna check the card value in the switch statement and print corrent information about the card. here sample code:
|
Author: | TerranceN [ Sat Jul 31, 2010 10:11 pm ] | ||||
Post subject: | RE:Switch Statement Help | ||||
Case statements by default fall through, meaning that it will just continue going line by line executing statements, like so:
in order to tell the computer you want to exit the case statement, use the break keyword:
Hope that helps. EDIT: Also, you are using a very brute force approach to this problem, try using integer division and remainders to figure out what the name of the card is. |
Author: | bfh [ Sun Aug 01, 2010 2:00 pm ] |
Post subject: | RE:Switch Statement Help |
Thanks for help, but what type of code would i use to figure our your division code would look like. im kinda brain dead atm, so i might figure it out later. im planing to use arrays in a later version, gonna rewrite code at a later time, for the time being just trying to get this to work then i worry about code size. thanks testing your code for case statements now |
Author: | DemonWasp [ Sun Aug 01, 2010 3:50 pm ] |
Post subject: | RE:Switch Statement Help |
This is easier if you start at 0 and go to 51, instead of 1-52. It works out the same, but the code is simpler. First, notice that the suit is determined by the card value divided by 13 (the number of cards in a suit), rounded down. This gives you a number in the range 0-3, which you could say is one of ["Clubs", "Diamonds", "Hearts", "Spades"]. Let this number be the suit. Then, notice that the card value is then the value modulus 13 (the remainder after dividing by 13). This gives you a number in the range 0-12, which we could call [ "Ace", "Two", "Three", ... , "King" ]. Let this number be the value. Then all you need to do to construct your final string is the following: printf ( "Card drawn is the %s of %s\n", values[value], suits[suit] ); The code for this should take maybe 5-8 lines, total. |
Author: | bfh [ Sun Aug 01, 2010 4:47 pm ] |
Post subject: | RE:Switch Statement Help |
Ill try playing around with that later, little trouble getting the explaination but i read your idea real quick. thanks for positive input. ima try this code on later, but it sounds a hell of a lot better that what i wrote. |