• 九度OJ 1103:二次方程计算器 (解方程)


    时间限制:1 秒

    内存限制:32 兆

    特殊判题:

    提交:2804

    解决:633

    题目描述:

    设计一个二次方程计算器

    输入:

    每个案例是关于x的一个二次方程表达式,为了简单,每个系数都是整数形式。

    输出:

    每个案例输出两个实数(由小到大输出,中间由空格隔开),保留两位小数;如果无解,则输出“No Solution”。

    样例输入:
    x^2+x=3x+4
    样例输出:
    -1.24 3.24
    来源:
    2011年上海交通大学计算机研究生机试真题

    思路:

    解方程的题,没有什么复杂的思路,主要是正确的读入方程系数,然后根据各种不同情况求解。


    代码:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <math.h>
     
    int main(void)
    {
        int n, i;
        int a, b, c;
        int flag, side, num;
        char s[100];
     
        while (scanf("%s", s) != EOF)
        {
            n = strlen(s);
            i=0;
            flag = 1;
            side = 1;
            num = 0;
            a = b = c = 0;
            while (i<n)
            {
                if (s[i] == '=')
                {
                    side *= -1;
                    i++;
                    continue;
                }
                flag = 1;
                if (s[i] == '+' || s[i] == '-')
                {
                    if (s[i] == '-')
                        flag = -1;
                    i++;
                }
                num = 1;
                if (isdigit(s[i]))
                {
                    num = atoi(s+i);
                    while (isdigit(s[i]))
                        i++;
                }
                if (s[i] == 'x')
                {
                    if (n-i>=3 && strncmp(s+i, "x^2", 3) == 0)
                    {
                        a += num*flag*side;
                        i += 3;
                    }
                    else
                    {
                        b += num*flag*side;
                        i += 1;
                    }
                }
                else
                {
                    c += num*flag*side;
                    i++;
                }
            }
            //printf("%dx^2+(%d)x+(%d)=0
    ", a, b, c);
            int delta = b*b-4*a*c;
            if (delta < 0)
                printf("No Solution
    ");
            else
            {
                double res1 = (-b-sqrt((double)delta))/2/a;
                double res2 = (-b+sqrt((double)delta))/2/a;
                printf("%.2lf %.2lf
    ", res1, res2);
            }
        }
     
        return 0;
    }
    /**************************************************************
        Problem: 1103
        User: liangrx06
        Language: C
        Result: Accepted
        Time:0 ms
        Memory:928 kb
    ****************************************************************/


    编程算法爱好者。
  • 相关阅读:
    python之enumerate枚举 第二篇(六):enumerate枚举
    git使用学习
    Git安装
    eclipse对项目整理分类
    Java基础学习总结——Java对象的序列化和反序列化
    工作代码实例
    substring与substr
    第一个jave程序-helloworld
    UI自动化
    sikuli实例
  • 原文地址:https://www.cnblogs.com/liangrx06/p/5083929.html
Copyright © 2020-2023  润新知