從鍵盤輸入兩個實數,然后輸入以下字符中的一個
+ - * /
程式根據輸入的字符,對之前輸入的兩個實數進行相應的數學運算并輸出計算結果。
uj5u.com熱心網友回復:
#include <stdio.h>
#include <math.h>
float get_result(float a, char opt, float b);
int main(void)
{
char opt1, opt2;
float a, b, c, result;
int choice;
printf("Please input your choice: (1: two number opt, 2: three nubers opt)");
scanf("%d", &choice);
if (choice != 1 && choice != 2) {
printf("Input error!\n");
return -1;
}
if (choice == 1) {
printf("Please input your operation: (eg: 1*2)");
scanf("%f%c%f", &a, &opt1, &b);
printf("=%.2f\n", get_result(a, opt1, b));
return 0;
}
printf("Please input your operation: (eg: 1*2*3)");
scanf("%f%c%f%c%f", &a, &opt1, &b, &opt2, &c);
if (opt1 == '*' || opt1 == '/') {
result = get_result(a, opt1, b);
printf("=%.2f\n", get_result(result, opt2, c));
} else if (opt2 == '*' || opt2 == '/') {
result = get_result(b, opt2, c);
printf("=%.2f\n", get_result(a, opt1, result));
}
return 0;
}
float get_result(float a, char opt, float b)
{
float result;
switch (opt) {
case '+':
result = a+b;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
if (fabsf(b) > 1e-6)
result = a/b;
break;
}
return result;
}
供參考~
可以在這個基礎上改一改~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/91623.html
標籤:C語言
上一篇:leetcode 的第17提題,請幫忙找出代碼中的問題
下一篇:求大佬指導一下c語言小程式!
