In: Computer Science
In the game of blackjack, the cards 2 through 10 are counted at their face values, regardless of suit; all face cards (jack, queen, and king) are counted as 10; and an ace is counted as a 1 or 11, depending on the total count of all cards in a player’s hand. The ace is counted as 11 only if the resulting total value of all cards in a player’s hand doesn’t exceed 21; otherwise, it’s counted as 1. Using this information, write a C++ program that accepts three card values as inputs (a 1 corresponding to an ace, a 2 corresponding to a two, and so on), calculates and display the total value of the hand, and the sum of the three cards.
>Answer
Code:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
int getCardValue(int points, int card) {
// Ace is 11 points if total sum does not exceeds 21
// else it is 1 point
if(card == 1){
if(points + 11 < 21)
return 11;
return 1;
}
//Cards value equals their number from 2 to 10
if(card >= 2 && card <= 10)
return card;
//J Q K have 10 points
if(card >= 11 && card <= 13)
return 10;
return 0;
}
void printCardSymbol(int card) {
if(card == 1)
printf("A ");
else if(card == 11)
printf("J ");
else if(card == 12)
printf("Q ");
else if(card == 13)
printf("K ");
else
printf("%d ",card);
return;
}
/* Cards:
* 1 - Ace
* [2,10] - face cards from two to ten
* 11 - J
* 12 - Q
* 13 K
*/
void blackjack() {
// Get random number from 1 to 13
int card1 = rand()%13 + 1;
// Get random number from 1 to 13
int card2 = rand() % 13 + 1;
// Get random number from 1 to 13
int card3 = rand() % 13 + 1;
// Sort card so A will be last elelent
// to add to total numbers
// If it is first number we might get error
// E.X. A 10 Q - AT first sum is zero so
// if we check A we get 11 points but total sum
// of two other cards is 20 and A can not be 11, it is 1
// So to avoid such errors we should check it at first.
if (card1 == 1) {
int tmp = card1;
card1 = card3;
card3 = tmp;
}
if(card2 == 2){
int tmp = card2;
card2 = card3;
card3 = tmp;
}
//Total Points, initialy equals to zero
int totalPoints = 0;
//We add each cards value to total points
totalPoints += getCardValue(totalPoints, card1);
totalPoints += getCardValue(totalPoints, card2);
totalPoints += getCardValue(totalPoints, card3);
//Print summery
printf("Player got cards: ");
printCardSymbol(card1);
printCardSymbol(card2);
printCardSymbol(card3);
printf("\n Player total points: %d",totalPoints);
}
int main() { blackjack ();}
Output:
Your Output (stdout) Player got cards: Q 10 A Player total points:
21