Advertisement
frares

Untitled

Aug 12th, 2022
1,191
0
129 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. // Write a software function that computes arithmetic number operations defined
  2. // as strings. The results should be returned as integers.
  3. // For simplicity, the possible operations can only be additions and/or subtractions.
  4.  
  5. #include <stdio.h>
  6.  
  7.  
  8. const char name[] = "Francisco José Alonso Ares"; // Please enter your name here
  9. //const char name[] = "Ion Popescu"; // as such
  10.  
  11. int arithmetic_operation(const char *input_string)
  12. {
  13.     int result;
  14.     // Your code goes here
  15.     int partial_number = 0;
  16.    
  17.     enum _operations {
  18.         op_plus,
  19.         op_minus,
  20.         op_null
  21.     } ;
  22.    
  23.     _operations operation = op_null;
  24.    
  25.     bool operation_plus = false;
  26.    
  27.     while (*input_string != 0) {
  28.         if ( *input_string == '+') {
  29.             if (operation == op_null) {
  30.                 result = partial_number;
  31.             } else {
  32.                 result -= partial_number;
  33.             }
  34.             partial_number = 0;
  35.             operation = op_plus;
  36.         } else if (*input_string == '-') {
  37.             if (operation == op_null) {
  38.                 result = partial_number;
  39.             } else {
  40.                 result -= partial_number;
  41.             }
  42.             partial_number = 0;
  43.             operation = op_minus;
  44.            
  45.         } else {
  46.             partial_number *= 10;
  47.             partial_number += *input_string - 0x30;
  48.         }    
  49.        
  50.        
  51.        
  52.         input_string++;
  53.     }
  54.     switch ( operation ) {
  55.         case  op_plus :
  56.             result += partial_number;
  57.             break;
  58.         case op_minus :
  59.             result -= partial_number;
  60.             break;
  61.     }
  62.    
  63.    
  64.  
  65.     return result;
  66. }
  67.  
  68. int main()
  69. {
  70.     printf("%d\n", arithmetic_operation("1+2"));        // Prints 3
  71.     printf("%d\n", arithmetic_operation("1-2"));        // Prints -1
  72.     printf("%d\n", arithmetic_operation("123-456+789"));    // Prints 456
  73.  
  74.     return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement