You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言方程化简程序异常:首个结果缺失等号

C语言方程化简程序的Bug排查与修复

问题描述

开发一款用于化简数学方程的C语言程序,核心功能是移除系数为零的项。测试时发现首个方程的化简结果不符合预期:

实际输出:

Original Equation: a + 0b = 0c + 2d + 0e + 0f
Simplified Equation: a+2d

预期输出:

Original Equation: a + 0b = 0c + 2d + 0e + 0f
Simplified Equation: a=2d

化简规则:

  • 保留非零系数项
  • 保留原方程中的+和=符号
  • 若原方程末尾是零系数项,移除最后一个+

问题根源分析

  1. =符号未被正确保留:原代码将=和+同等处理,仅当termFound为1时才添加该符号。但在处理0b这类零系数项后,termFound被重置为0,导致遇到=时未将其加入化简结果。
  2. 零系数项跳过逻辑不完整:跳过零系数项的循环仅判断跳过到空格或+,未考虑=符号,可能导致后续字符处理异常。

修正后的代码

#include <stdio.h>
#include <string.h>
#include <ctype.h>

// 移除系数为零的项,化简方程
void simplifyEquation(const char equation[]) {
    char simplifiedEquation[100];
    int simplifiedPos = 0;
    int len = strlen(equation);
    int termFound = 0; // 标记是否找到有效非零项

    for (int i = 0; i < len; i++) {
        if (equation[i] == '+') {
            // 仅当之前存在有效项时,才添加+
            if (termFound) {
                simplifiedEquation[simplifiedPos++] = equation[i];
                termFound = 0;
            }
        } else if (equation[i] == '=') {
            // =是方程分隔符,必须保留,不受termFound影响
            simplifiedEquation[simplifiedPos++] = equation[i];
            termFound = 0;
        } else if (isdigit(equation[i])) {
            if (equation[i] == '0') {
                // 跳过整个零系数项,直到遇到空格、+或=
                while (i < len && equation[i] != ' ' && equation[i] != '+' && equation[i] != '=') {
                    i++;
                }
                continue;
            }
            // 添加非零系数的数字部分
            simplifiedEquation[simplifiedPos++] = equation[i];
            termFound = 1;
        } else if (isalpha(equation[i])) {
            // 添加变量部分
            simplifiedEquation[simplifiedPos++] = equation[i];
            termFound = 1;
        }
        // 空格直接跳过,不加入结果
    }

    // 移除末尾多余的+
    if (simplifiedPos > 0 && simplifiedEquation[simplifiedPos - 1] == '+') {
        simplifiedEquation[simplifiedPos - 1] = '\0';
    } else {
        simplifiedEquation[simplifiedPos] = '\0';
    }

    printf("Original Equation: %s\n", equation);
    printf("Simplified Equation: %s\n", simplifiedEquation);
}

int main() {
    const char equations[][100] = {
        "a + 0b = 0c + 2d + 0e + 0f",
        "a + b = 0c + 2d + 0e + 0f",
        "a + 2b = 0c + 2d + 0e + 2f",
        "a + 2b = 0c + 2d + 0e + 0f"
    };

    for (int i = 0; i < sizeof(equations) / sizeof(equations[0]); i++) {
        simplifyEquation(equations[i]);
        printf("\n");
    }

    return 0;
}

关键修改点

  • 单独处理=符号:无论termFound状态如何,直接将=加入化简结果,确保方程结构完整。
  • 完善零系数项跳过逻辑:在循环条件中加入=,确保完整跳过零系数项直到方程分隔符。
  • 明确忽略空格:直接跳过空格,使化简结果更简洁(符合预期格式)。

内容的提问来源于stack exchange,提问作者Unsigned Index

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:54:52