daniel_lawson9999

Calculator

Oct 1st, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int main(int argc, string argv[])
  5. {
  6.     if (argc != 4) //make sure the user inputs 4 arguments
  7.     {
  8.         printf("Please enter two numbers and an operation (./calc 4 + 4)\n");
  9.         return 1;
  10.     }
  11.     float num1 = atof(argv[1]); //get the first number
  12.     float num2 = atof(argv[3]); //get the second
  13.     char op = argv[2][0]; //get the operator
  14.     float output;
  15.     if (op == '+') //if addition
  16.     {
  17.         output = num1 + num2;
  18.     }
  19.     else if (op == '-') //if subtraction
  20.     {
  21.         output = num1 - num2;
  22.     }
  23.     else if (op == 'x') //if multiplication
  24.     {
  25.         output = num1 * num2;
  26.     }
  27.     else if (op == '/') //if division
  28.     {
  29.         output = num1 / num2;
  30.     }
  31.     else if (op == '%') //if module
  32.     {
  33.         output = ((float)(( (int)(num1 * 1000)) % ( (int)(num2 * 1000)))) / 1000;
  34.         /*multiple each number by 1000 and convert to int, then preform module operation
  35.         convert to a float, then divide by 1000
  36.         */
  37.     }
  38.     else
  39.     {
  40.         printf("enter a valid operator (+,-,x,/,%%");
  41.         return 1;
  42.     }
  43.     printf("%.6f\n", output);
  44.     return 0;
  45. }
  46.  
  47.  
  48.  
  49. /*desired output exampel
  50. ~/workspace/chapter2/ $ ./calc 4 + 5
  51. 9.000000
  52. or, indeed like this (allowing the user to perform some basic floating-point arithmetic)
  53.  
  54. ~/workspace/chapter2/ $ ./calc 8.38 - 5.12
  55. 3.260000
  56. */
Advertisement
Add Comment
Please, Sign In to add comment