CodeForces 20B Equation (简单题)

来源:互联网 发布:vesa图形编程系统 pdf 编辑:程序博客网 时间:2024/05/29 15:43
题目类型  简单题

题目意思
给你一个一元二次方程 A*x*x + B*x + c = 0, 求解的数量

解题方法
1.无穷个解的情况 -> A == 0 && B == 0 && C == 0
2.一个解的情况   -> (A == 0 && B != 0) 或 (A != 0 && B*B - 4 * A * C == 0)
3.两个解的情况   -> A != 0 && B * B - 4 * A * C > 0

注意
1.如果用 int 保存 A, B, C 那么由于 -1e5 <= A, B, C <= 1e5, B*B 或 4*A*C 的值会溢出 int的范围
  所以要用 long long 或 double, 记住用 double 的时候判断是否相等时不能直接用 ==, 而是判断 要比较的两个数的绝对值是否小于一个很小的值
2.两个解的情况时要按升序输出, 且最少保留5位小数

参考代码 - 有疑问的地方在下方留言 看到会尽快回复的
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>using namespace std;typedef long long LL;int main() {  LL a, b, c;  while(cin>>a>>b>>c) {    if(a == 0 && b == 0 && c == 0) printf("-1\n");    else if(a == 0 && b == 0) {      printf("0\n");    }    else if(a == 0) {      printf("1\n%.6lf\n", -c*1.0/b);    }    else {      LL B = b * b - 4 * a * c;      if(B > 0) {        double t = sqrt(b*b*1.0-4*a*c);        double x1 = (-b-t)/2/a, x2 = (-b+t)/2/a;        if(x1 < x2) printf("2\n%.6lf\n%.6lf\n", x1, x2);        else printf("2\n%.6lf\n%.6lf\n", x2, x1);      }      else if(B == 0) {        printf("1\n%.6lf\n", -b/2.0/a);      }      else printf("0\n");    }  }  return 0;}


0 0
原创粉丝点击