Home > Article > Computer Tutorials > Write four arithmetic operations programs in c language
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 '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 != 0) { result = num1 / num2; } else { printf("除数不能为零。\n"); return 1; // 退出程序 } break; default: printf("无效的运算符。\n"); return 1; // 退出程序 } // 输出结果 printf("结果: %lf\n", result); return 0; }
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!