如何使用 C 语言编写一个简单的计算器程序?
从编写 C 代码创建一个简单的计算器开始。然后,按照下面给出的算法编写一个 C 程序。
算法
Step 1: Declare variables Step 2: Enter any operator at runtime Step 3: Enter any two integer values at runtime Step 4: Apply switch case to select the operator: // case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: printf("
Invalid Operator "); Step 5: Print the result
例如
以下是使用 Switch Case 的计算器 C 程序−
#include <stdio.h> int main(){ char Operator; float num1, num2, result = 0; printf("
Enter any one operator like +, -, *, / : "); scanf("%c", &Operator); printf("Enter the values of Operands num1 and num2
: "); scanf("%f%f", &num1, &num2); switch(Operator){ case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: printf("
Invalid Operator "); } printf("The value = %f", result); return 0; }
输出
当以上程序执行时,它会产生以下结果 −
Enter any one operator: + Enter values of Operands num1 and num2: 23 45 The value = 68.000000
广告