本文共 2420 字,大约阅读时间需要 8 分钟。
c语言的字符串处理还是有点繁琐的,今天手敲了一遍代码,写的不是很好,有很大改进空间。
待改进思路:
使用= 作为分隔符,将字符分割成两段
将-改成+-号,统一使用+号进行分割处理
atoi 可以处理+ - 符号,代码里面居然没有利用起来,有点挫,下次改进。
经验总结:
写这种需要考虑全面的代码前一定要写号测试用例,否则后面调试的时候花费的时间会非常长,养成编程的号习惯。
#include <stdio.h>
#include <string.h> #include <stdlib.h>// overflow , to long ?
#define LEFT 0 // = LEFT
#define RIGHT 1 // = RIGHT int g_dir = LEFT; int g_lx; int g_rnum;// void handle_x
void handle_x(char *ele) { int x = 0;if (ele[0] == '-') {
x -= atoi(&ele[1]); } else if (ele[0] == '+'){ x += atoi(&ele[1]); } else { x = atoi(ele); }//
if (g_dir == LEFT) { g_lx += x; } else { g_lx -= x; } }void handle_nums(char *ele)
{ int x = 0;if (ele[0] == '-') {
x -= atoi(&ele[1]); } else if (ele[0] == '+'){ x += atoi(&ele[1]); } else { x = atoi(ele); }//
if (g_dir == LEFT) { g_rnum -= x; } else { g_rnum += x; } }void handle_data(char *ele)
{ // handle '=' ? CHANGE DIR int len; char tmp_str[15]; char first_str[15];if (ele[0] == '=') {
g_dir = RIGHT; strcpy(first_str, &ele[1]); // securec func? } else { strcpy(first_str, ele); }len = strlen(ele);
if (ele[len - 1] == 'x') {
// x single ? if (first_str[0] == 'x') { handle_x("1"); } else if (first_str[0] == '-' && first_str[1] == 'x') { handle_x("-1"); } else if (first_str[0] == '+' && first_str[1] == 'x') { handle_x("1"); } else { len = strlen(first_str); first_str[len - 1] = '\0'; handle_x(first_str); } } else { // handle data handle_nums(first_str); } }void init_data(void)
{ g_dir = LEFT; g_lx = 0; g_rnum = 0; }void get_result(char *res)
{ int ans;if (g_lx == 0) {
if (g_rnum == 0) { // infiinite sprintf(res, "Infinite solutions"); } else { // no solution sprintf(res, "No solution"); } } else { ans = g_rnum / g_lx; sprintf(res, "x=%d", ans); // secrue func } }char * solveEquation(char * equation){
// char res[20]; char *res = NULL; int len; int i; int ele_start = 0; char ele[15];res = (char *)malloc(30 * sizeof(char));
// res == null memset(res, 0, 30 * sizeof(char)); // return checkif (equation == NULL) {
return NULL; }init_data();
// solve_data len = strlen(equation); for (i = 0; i <= len; i++) { // = handle if (equation[i] == '+' || equation[i] == '-' || equation[i] == '=' || equation[i] == '\0') { strncpy(ele, &equation[ele_start], i - ele_start); if (i - ele_start == 0) { continue; } ele[i - ele_start] = '\0'; // +5 OR =6 ... handle_data(ele); ele_start = i; // = hanle ? i ele to be in the next ele } }get_result(res);
return res;
}转载地址:http://ciloi.baihongyu.com/