Write four arithmetic operations programs in c language

WBOY
Release: 2024-01-04 15:26:00
forward
2742 people have browsed it

1. Use C language to write a program that can perform four arithmetic operations

The following is a simple C language program for performing four arithmetic operations on two numbers. The program accepts two numbers and operators input by the user and outputs the calculation result.

#include <stdio.h>

int main() {
    // 定义变量
    double num1, num2, result;
    char operator;

    // 获取用户输入
    printf("请输入第一个数: ");
    scanf("%lf", &num1);

    printf("请输入运算符 (+, -, *, /): ");
    scanf(" %c", &operator);  // 注意空格,以防止读取上一个输入的换行符

    printf("请输入第二个数: ");
    scanf("%lf", &num2);

    // 进行四则运算
    switch (operator) {
        case &#39;+&#39;:
            result = num1 + num2;
            break;
        case &#39;-&#39;:
            result = num1 - num2;
            break;
        case &#39;*&#39;:
            result = num1 * num2;
            break;
        case &#39;/&#39;:
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                printf("除数不能为零。\n");
                return 1;  // 退出程序
            }
            break;
        default:
            printf("无效的运算符。\n");
            return 1;  // 退出程序
    }

    // 输出结果
    printf("结果: %lf\n", result);

    return 0;
}
Copy after login

2. Summary

The above C language program implements the four basic arithmetic operations through user input, including addition, subtraction, multiplication and division. Use the switch statement to perform corresponding operations based on the input operators and output the results. The program adds judgment on the case where the divisor is zero during division. In practical applications, it can be further expanded and optimized as needed.

The above is the detailed content of Write four arithmetic operations programs in c language. For more information, please follow other related articles on the PHP Chinese website!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template