fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. // Function to get the value of a single card
  5. int get_card_value(char card) {
  6. card = toupper(card); // Convert to uppercase for consistency
  7. if (card >= '2' && card <= '9') {
  8. return card - '0'; // Convert char '2'-'9' to integer 2-9
  9. } else if (card == 'T' || card == 'K' || card == 'Q' || card == 'J') {
  10. return 10; // Face cards are worth 10 points
  11. } else if (card == 'A') {
  12. return 11; // Aces are worth 11 points by default
  13. } else {
  14. return -1; // Invalid card
  15. }
  16. }
  17.  
  18. // Function to calculate the total value of a two-card blackjack hand
  19. int blackjack_hand_value(char card1, char card2) {
  20. /**
  21.   * Calculate the point total of a two-card blackjack hand.
  22.   *
  23.   * Parameters:
  24.   * - card1: The first card in the hand ('2'-'9', 'T', 'K', 'Q', 'J', 'A').
  25.   * - card2: The second card in the hand ('2'-'9', 'T', 'K', 'Q', 'J', 'A').
  26.   *
  27.   * Returns:
  28.   * - int: The point total of the hand.
  29.   * - -1: If invalid input is provided.
  30.   */
  31.  
  32. // Get the values of the two cards
  33. {
  34. int value1 = get_card_value(card1);
  35. int value2 = get_card_value(card2);
  36.  
  37. // Check for invalid input
  38. if (value1 == -1 || value2 == -1) {
  39. return -1; // Return -1 to indicate an error
  40. }
  41.  
  42. // Calculate the total value of the hand
  43. int total = value1 + value2;
  44. if (total == 22)
  45. {
  46. total = 11;
  47. }
  48. // Adjust for multiple aces (if both cards are aces)
  49. return total;
  50. }
  51. }
  52.  
  53. int main() {
  54. // Example usage
  55. char card1, card2;
  56.  
  57. printf("Enter the first card (2-9, T, K, Q, J, A): ");
  58. scanf(" %c", &card1);
  59.  
  60. printf("Enter the second card (2-9, T, K, Q, J, A): ");
  61. scanf(" %c", &card2);
  62.  
  63. int total = blackjack_hand_value(card1, card2);
  64.  
  65. if (total == -1) {
  66. printf("Invalid card input. Please enter valid cards.\n");
  67. } else {
  68. printf("The total value of the hand is: %d\n", total);
  69. }
  70.  
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Enter the first card (2-9, T, K, Q, J, A): Enter the second card (2-9, T, K, Q, J, A): Invalid card input. Please enter valid cards.