bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / letusc / luc098.c

luc098.c (1811B)


      1 /* Write a calculator utility using command line arguments.\nUsage: calc <switch> <n> <m>\nwhere switch is arithmetic operator or comparison operator.
      2 */
      3 /* Let Us C, Chap- 20 (More Issues In Input/Output), Qn No.: A(d) */
      4 
      5 /* This file is auto-generated by a bot. */
      6 /* This code is not compiled; it is for reference only. */
      7 
      8 
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <string.h>
     12 #include <ctype.h>
     13 
     14 int main(int argc, char *argv[])
     15 {
     16     float n, m, res;
     17     char operator;
     18 
     19     if (argc != 4)
     20     {
     21         printf("Usage: %s <switch> <n> <m>\n", argv[0]);
     22         printf("Example: %s + 10 20\n", argv[0]);
     23         printf("Note: For multiplication (*), use '*' or x to avoid shell expansion.\n");
     24         exit(1);
     25     }
     26 
     27     operator = argv[1][0]; // First character of the switch argument
     28     n = atof(argv[2]);
     29     m = atof(argv[3]);
     30 
     31     switch (operator)
     32     {
     33     // Arithmetic
     34     case '+':
     35         printf("%.2f\n", n + m);
     36         break;
     37     case '-':
     38         printf("%.2f\n", n - m);
     39         break;
     40     case 'x': 
     41     case '*':
     42         printf("%.2f\n", n * m);
     43         break;
     44     case '/':
     45         if (m == 0) printf("Error: Division by zero\n");
     46         else printf("%.2f\n", n / m);
     47         break;
     48     case '%':
     49         printf("%d\n", (int)n % (int)m);
     50         break;
     51 
     52     // Comparison
     53     case '<':
     54         printf("%s\n", (n < m) ? "True" : "False");
     55         break;
     56     case '>':
     57         printf("%s\n", (n > m) ? "True" : "False");
     58         break;
     59     
     60     // Handling symbols that might be multi-char (e.g. <=, >=, ==) is tricky 
     61     // with argv[1][0], but basic logic for typical single char switches:
     62     case '=':
     63         printf("%s\n", (n == m) ? "True" : "False");
     64         break;
     65 
     66     default:
     67         printf("Unknown operator: %c\n", operator);
     68         break;
     69     }
     70 
     71     return 0;
     72 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror