洛谷2378 因式分解 字符串

洛谷2378 因式分解 字符串

简单好玩的字符串处理小水题~~

(话说自从我写完那道配平化学方程式的字符串处理+解方程题,碰到这种题就越发的兴奋了 =、=)

数据

这个题数据比较友好, 最多最多会给你一个二次三项式 进行因式分解  -> 即变成(x+a)(x+b)形式

不就是 -> 一般式转两根式嘛

处理完字符串直接带入公式解一元二次方程即可    当然还要注意很多很多小细节

代码

#include<bits/stdc++.h>
using namespace std;
char s[128];
long long i,len,a,b,c;
int get(){
    int sum=0,t=1;
    if(s[i]=='+')t=1;
    else if(s[i]=='-')t=-1;
    i++;
    while(s[i]>='0'&&s[i]<='9')sum=sum*10+s[i++]-'0';
    if(sum==0)return 1*t;
    return sum*t;
} 
int main()
{
    scanf("%s",s);
    len=strlen(s);
    if(s[1]!='^'||len==1||len==3){
        printf("%s
",s);
        return 0;
    }
    a=1;
    i=3;
    b=get();
    if(s[i]!='x')c=b,b=0;
    i++;
    if(len>i)c=get();
    long long x1=(sqrt(b*b-4*a*c)-b)/2/a,
        x2=(-sqrt(b*b-4*a*c)-b)/2/a;
    x1=-x1,x2=-x2;
    if(x1<x2)swap(x1,x2);
//    printf("%d %d %d %d %d",a,b,c,x1,x2);
    if(x1==x2){
        if(x1>0)printf("(x+%d)^2",x1);
        else printf("(x%d)^2",x1);
    }
    else{
        if(x1>0)printf("(x+%d)",x1);    
        else if(x1<0) printf("(x%d)",x1);
        else printf("x");
        if(x2>0)printf("(x+%d)",x2);    
        else if(x2<0)printf("(x%d)",x2);
        else printf("x");
    }
    printf("
");
    return 0;
}  
原文地址:https://www.cnblogs.com/Elfish/p/7695078.html