SHARE
TWEET

Untitled

a guest Mar 20th, 2017 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * lab1.c: someone's homework
  3.  *
  4.  * Someone
  5.  * March 21, 2017
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <math.h>
  10.  
  11. /* Defines the valid operations available to the user. */
  12. typedef enum {
  13.     OP_ADD = 'A',
  14.     OP_LOG = 'T',
  15.     OP_TERMINATE = '#'
  16. } Token;
  17.  
  18. /* Converts a character (either 0 or 1) to an integer value. */
  19. int char_to_bit(char c)
  20. {
  21.     if (c == '0') {
  22.         return 0;
  23.     } else if (c == '1') {
  24.         return 1;
  25.     } else {
  26.         /* FIXME: We receive a newline somewhere in build_number.
  27.          * This code is always executed when accepting a new number.
  28.          * Find a way to get rid of it!
  29.          */
  30.         return 0;
  31.     }
  32. }
  33.  
  34. /* Appends either a zero or one to a number. */
  35. void append_bit(double *num, char c)
  36. {
  37.     int bit = char_to_bit(c);
  38.  
  39.     *num *= 2;
  40.     *num += bit;
  41. }
  42.  
  43. /* Accepts input until OP_TERMINATE is reached and builds an integer
  44.  * from its binary representation.
  45.  */
  46. void build_number(double *num)
  47. {
  48.     char c;
  49.  
  50.     while ((c = getchar()) != OP_TERMINATE)
  51.     {
  52.         append_bit(num, c);
  53.     }
  54. }
  55.  
  56. int main(int argc, char *argv[])
  57. {
  58.     double input_1, input_2, result;
  59.  
  60.     Token tok;
  61.     char c;
  62.  
  63.     scanf(" %c", &tok);
  64.  
  65.     switch (tok)
  66.     {
  67.         case OP_ADD:
  68.             build_number(&input_1);
  69.             build_number(&input_2);
  70.  
  71.             result = input_1 + input_2;
  72.  
  73.             break;
  74.        
  75.         case OP_LOG:
  76.             build_number(&input_1);
  77.  
  78.             result = log10(input_1);
  79.  
  80.             break;
  81.  
  82.         default:
  83.             /* TODO: Exit gracefully when no valid operation is given. */
  84.             break;
  85.     }
  86.  
  87.     printf("%.2f\n", result);
  88.  
  89.     return 0;
  90. }
RAW Paste Data
Top