18.08.04 P1022 计算器的改良
题目背景
NCLNCL 是一家专门从事计算器改良与升级的实验室,最近该实验室收到了某公司所委托的一个任务:需要在该公司某型号的计算器上加上解一元一次方程的功能。实验室将这个任务交给了一个刚进入的新手ZL先生。
题目描述
为了很好的完成这个任务, ZLZL 先生首先研究了一些一元一次方程的实例:
4+3x=84+3x=8
6a-5+1=2-2a6a−5+1=2−2a
-5+12y=0−5+12y=0
ZLZL 先生被主管告之,在计算器上键入的一个一元一次方程中,只包含整数、小写字母及+、-、=这三个数学符号(当然,符号“-”既可作减号,也可作负号)。方程中并没有括号,也没有除号,方程中的字母表示未知数。
你可假设对键入的方程的正确性的判断是由另一个程序员在做,或者说可认为键入的一元一次方程均为合法的,且有唯一实数解。
输入输出格式
输入格式:
一个一元一次方程。
输出格式:
解方程的结果(精确至小数点后三位)。
输入输出样例
输出样例#1:
View Code
a=0.750
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdlib> 3 #include<cstdio> 4 #include <string> 5 #include <cstring> 6 #include <algorithm> 7 #include<map> 8 #include <math.h> 9 using namespace std; 10 11 12 int main() 13 { 14 int n; 15 int X[2] = { 0 }, Con[2] = { 0 }; 16 char x, line[100] = { 0 }; 17 char ch='+'; 18 int flag = 0; 19 scanf("%s", line); 20 int l = strlen(line); 21 line[l] = '+'; 22 for (int i = 0; line[i] != '\0'; i++) { 23 if (line[i] <= 'z'&&line[i] >= 'a') 24 { 25 x = line[i]; 26 if (!(line[i - 1] >= '0'&&line[i - 1] <= '9')) 27 { 28 if (ch == '+') 29 X[flag] += 1; 30 else 31 X[flag] += -1; 32 continue; 33 } 34 int tmp = 0; 35 for (int j = i - 1; line[j] >= '0'&&line[j] <= '9'; j--) 36 tmp += (line[j] - '0')*pow(10, i - j - 1); 37 if (ch == '+') 38 X[flag] += tmp; 39 else 40 X[flag] -= tmp; 41 } 42 else if (line[i] == '+' || line[i] == '-'||line[i]=='=') 43 { 44 int tmp = 0; 45 for (int j = i - 1; line[j] >= '0'&&line[j] <= '9'; j--) 46 tmp += (line[j] - '0')*pow(10, i - j - 1); 47 if (ch == '+') 48 Con[flag] += tmp; 49 else 50 Con[flag] -= tmp; 51 ch = line[i]; 52 if (line[i] == '=') { 53 ch = '+'; 54 flag = 1; 55 } 56 } 57 } 58 double ans=((double)Con[1]-(double)Con[0])/((double)X[0]-(double)X[1]); 59 if (Con[0] - Con[1] == 0) 60 ans = 0; 61 printf("%c=%.3f\n",x, ans); 62 return 0; 63 }
不难,但很繁
一开始没有考虑到算式开头是如 a 或 -a 这种形式的模块因而推翻重写了……
有许多细节要考虑,其中一个坑点是:貌似在浮点数运算中
[(double)a-(double)a]/(double)x=-0.000...
所以需要特判一下
注定失败的战争,也要拼尽全力去打赢它;
就算输,也要输得足够漂亮。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步