Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, string argv[])
- {
- if (argc != 4) //make sure the user inputs 4 arguments
- {
- printf("Please enter two numbers and an operation (./calc 4 + 4)\n");
- return 1;
- }
- float num1 = atof(argv[1]); //get the first number
- float num2 = atof(argv[3]); //get the second
- char op = argv[2][0]; //get the operator
- float output;
- if (op == '+') //if addition
- {
- output = num1 + num2;
- }
- else if (op == '-') //if subtraction
- {
- output = num1 - num2;
- }
- else if (op == 'x') //if multiplication
- {
- output = num1 * num2;
- }
- else if (op == '/') //if division
- {
- output = num1 / num2;
- }
- else if (op == '%') //if module
- {
- output = ((float)(( (int)(num1 * 1000)) % ( (int)(num2 * 1000)))) / 1000;
- /*multiple each number by 1000 and convert to int, then preform module operation
- convert to a float, then divide by 1000
- */
- }
- else
- {
- printf("enter a valid operator (+,-,x,/,%%");
- return 1;
- }
- printf("%.6f\n", output);
- return 0;
- }
- /*desired output exampel
- ~/workspace/chapter2/ $ ./calc 4 + 5
- 9.000000
- or, indeed like this (allowing the user to perform some basic floating-point arithmetic)
- ~/workspace/chapter2/ $ ./calc 8.38 - 5.12
- 3.260000
- */
Advertisement
Add Comment
Please, Sign In to add comment