📜  Calculator_C (1)

📅  最后修改于: 2023-12-03 15:29:56.065000             🧑  作者: Mango

Calculator_C

Introduction

Calculator_C is a simple calculator program written in C that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

It is a command-line program that provides a user-friendly interface to perform the above-mentioned arithmetic operations with two numbers.

Features

Calculator_C has the following features:

  • Addition of two numbers
  • Subtraction of two numbers
  • Multiplication of two numbers
  • Division of two numbers
  • Error handling for division by zero
Usage

To use Calculator_C, follow these steps:

  1. Open the command prompt/terminal.
  2. Navigate to the directory where the Calculator_C executable is stored.
  3. Enter the command calculator_c followed by the operation and two numbers to perform the arithmetic operation.

The syntax for the commands is as follows:

  • To perform addition: calculator_c add num1 num2
  • To perform subtraction: calculator_c sub num1 num2
  • To perform multiplication: calculator_c mul num1 num2
  • To perform division: calculator_c div num1 num2
Code

Here is the code snippet for the main function of the Calculator_C program:

int main(int argc, char *argv[]) {
    if (argc != 4) {
        printf("Error: Invalid number of arguments!\n");
        exit(0);
    }

    double num1 = atof(argv[2]);
    double num2 = atof(argv[3]);
    double result = 0;

    if (strcmp(argv[1], "add") == 0) {
        result = num1 + num2;
    }
    else if (strcmp(argv[1], "sub") == 0) {
        result = num1 - num2;
    }
    else if (strcmp(argv[1], "mul") == 0) {
        result = num1 * num2;
    }
    else if (strcmp(argv[1], "div") == 0) {
        if (num2 == 0) {
            printf("Error: Division by zero!\n");
            exit(0);
        }
        result = num1 / num2;
    }
    else {
        printf("Error: Invalid operation!\n");
        exit(0);
    }

    printf("Result: %lf\n", result);
    return 0;
}

As can be seen from the code snippet, the program takes in the command-line arguments and performs the arithmetic operation based on the first argument passed. If the number of arguments is invalid, or any other error occurs, the program exits with an error message.