【问题标题】:Read the coefficients a,b,c of the quadratic equation ax^2+bx+c and print it roots nicely for imaginary roots print in x+iy form读取二次方程 ax^2+bx+c 的系数 a,b,c 并很好地打印它的根,以便以 x+iy 形式打印虚根
【发布时间】:2022-01-22 06:15:22
【问题描述】:
#include <math.h>
#include <stdio.h>

main() {
    int a, b, c, x, x1, x2;
    printf("enter the values of a,b,c:");
    scanf("%d%d%d", &a, &b, &c);
    printf("The quadratic equation is %d*pow(x,2)+%d*x+%d=0", a, b, c);

    if (pow(b, 2) - 4 * a * c >= 0) {
        x1 = (-b + sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
        x2 = (-b - sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
        printf("the roots of the equation are x1=%d,x2=%d", x1, x2);
    }
    else
        printf("roots of the equation in the form of x+iy and x-iy");

    return 0;
}

对于给定的问题,这段代码是否合适,我对打印虚构的根有点困惑。你能帮忙吗

【问题讨论】:

  • 您应该检查scanf 是否成功。 if(scanf("%d%d%d", &amp;a, &amp;b, &amp;c) == 3) { success } else { failure }
  • 对不起,我没明白你的意思,为什么应该是 ==3
  • 虽然 abc 可以成为 int,但我认为您希望 x1x2 成为 double (并使用%g 打印)
  • @user17725027 了解scanf 返回的内容,您就会明白为什么它应该是== 3
  • 很抱歉,我仍然没有得到,我怀疑我应该遵循什么步骤以 x+iy 的形式打印虚根,好吧,我理解 x1 和 x2 应该是双倍的,但是我的疑问呢

标签: c


【解决方案1】:
  1. 使用正确的main原型。
  2. 使用浮点数而不是整数
  3. pow(b,2) == b*b
  4. / 2 * a -> / (2 * a)
int main(void) {
    double a, b, c, x, x1, x2;
    printf("enter the values of a,b,c:");
    if(scanf("%lf %lf %lf", &a, &b, &c) != 3) { /* handle error */}
    printf("\nThe quadratic equation is %f*x^2+%f*x+%f=0\n", a, b, c);

    if (b*b - 4 * a * c >= 0) {
        x1 = (-b + sqrt(b*b - 4 * a * c)) / (2 * a);
        x2 = (-b - sqrt(b*b - 4 * a * c)) / (2 * a);
        printf("the roots of the equation are x1=%f,x2=%f\n", x1, x2);
    }
    else
    {
        double r = -b / (2*a);
        double z = sqrt(fabs(b*b - 4 * a * c));

        printf("the roots of the equation are x1 = %f + i%f, x2 = %f - i%f", r,z,r,z);
    }
}

https://gcc.godbolt.org/z/Ys1s8bWY7

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2011-07-24
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多