NOIP2000 普及组 - 计算器的改良:一元一次方程求解

题目背景

NCL 是一家专门从事计算器改良与升级的实验室,最近该实验室收到了某公司所委托的一个任务:需要在该公司某型号的计算器上加上解一元一次方程的功能。实验室将这个任务交给了一个刚进入的新手 ZL 先生。

题目描述

为了很好的完成这个任务,ZL 先生首先研究了一些一元一次方程的实例:

  • '4+3x=8'。
  • '6a-5+1=2-2a'。
  • '-5+12y=0'。

ZL 先生被主管告之,在计算器上键入的一个一元一次方程中,只包含整数、小写字母及 '+'、'-'、'=' 这三个数学符号(当然,符号“'-'”既可作减号,也可作负号)。方程中并没有括号,也没有除号,方程中的字母表示未知数。

你可假设对键入的方程的正确性的判断是由另一个程序员在做,或者说可认为键入的一元一次方程均为合法的,且有唯一实数解。

输入格式

一个一元一次方程。

输出格式

解方程的结果(精确至小数点后三位)。

样例 #1

样例输入 #1

6a-5+1=2-2a

样例输出 #1

a=0.750

C++ 代码

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main() {
    string equation;
    getline(cin, equation);

    // 将方程中的字母替换为 x
    for (int i = 0; i < equation.length(); i++) {
        if (isalpha(equation[i])) {
            equation[i] = 'x';
        }
    }

    // 将方程中的等号替换为空格
    for (int i = 0; i < equation.length(); i++) {
        if (equation[i] == '=') {
            equation[i] = ' ';
        }
    }

    // 去除方程中的空格
    equation.erase(remove_if(equation.begin(), equation.end(), isspace), equation.end());

    // 通过字符串流分割方程
    stringstream ss(equation);
    string term;

    double coefficient = 0;
    double constant = 0;

    while (getline(ss, term, '+')) {
        if (term.find('x') != string::npos) {
            size_t xIndex = term.find('x');
            string coefficientString = term.substr(0, xIndex);
            double termCoefficient = stod(coefficientString);
            coefficient += termCoefficient;
        } else {
            constant += stod(term);
        }
    }

    while (getline(ss, term, '-')) {
        if (term.find('x') != string::npos) {
            size_t xIndex = term.find('x');
            string coefficientString = term.substr(0, xIndex);
            double termCoefficient = stod(coefficientString);
            coefficient -= termCoefficient;
        } else {
            constant -= stod(term);
        }
    }

    double solution = -constant / coefficient;
    cout << 'x=' << fixed << setprecision(3) << solution << endl;

    return 0;
}
NOIP2000 普及组 - 计算器的改良:一元一次方程求解

原文地址: https://www.cveoy.top/t/topic/qz9n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录