如何使用3个系数求解C中的二次方程?

时间:2016-11-26 14:17:56

标签: c loops

我的教授告诉我们要写一个解决二次方程的程序,但他补充说,一开始他希望我们为每个a,b和c定义4组3个系数。换句话说,我必须为每个a,b和c定义4组3个不同的系数,并且一旦程序解决了a,b和c的第一组3个系数的等式,它就会继续并解决下一组3个定义的系数,直到所有4个集合都被解决。

我能够通过使用scanf定义每个a,b和c系数来编写一个解决二次方程的程序。你能帮忙吗,因为我无法在任何地方找到答案吗?

这就是我到目前为止所写的内容,它非常简单但有效。我在一个工程课程中,我们每周只有2小时的实验室,不会反映这些课程。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int as[4], bs[4], cs[4];
int a, b, c;
double root1,root2,discriminant, realpart, imaginarypart;
int main ()
{ 
    int i, n;
    printf("Enter how many coefficents do you want to eneter : ");
    scanf("%d",&n);
    for(i = 0; i < n; ++i)
    {
        printf("Enter you coefficents for a,b and c for set %d : \n", i+1);
        scanf("%d %d %d",&as[i],&bs[i],&cs[i]);
        a = as[i];
        b = bs[i];
        c = cs[i] ;
    }
    printf("a = %d %d %d\n", as[0], as[1], as[2]);
    printf("b = %d %d %d\n", bs[0], bs[1], bs[2]);
    printf("c = %d %d %d\n", cs[0], cs[1], cs[2]);

    for(i = 0; i < n; ++i)
    {
    discriminant = (b*b - 4*a*c);
    root1 = (-b - sqrt(discriminant))/(2*a);
    root2 = (-b + sqrt(discriminant))/(2*a);



    if (discriminant > 0 )
    {
    printf("Your set %d of roots is : \nroot1 = %lf\nroot2 = %lf\n", i+1,root1, root2); 
    }
    else if (discriminant == 0)  
    {
        printf("Your set %d of roots is : \nroot1 = root2 = %lf\n",i+1,root1);
    }
    else 
    {
        realpart = -b/(2*a);
        imaginarypart = sqrt(-discriminant)/(2*a);
        printf("Your set %d of roots is :\nroot1 = %lf + %lfi\nroot2 = %lf - %lfi\n",i+1,realpart, imaginarypart, realpart, imaginarypart);
    }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

你混合了2件事:定义 4套,从输入中读取(正如我从你的&#34;使用scanf&#34; )。

(从输入中读取它们没有问题,因为新的读取值会覆盖旧的。)

预先定义 4套可以通过 arrays 完成:

float as[4], bs[4], cs[4];        // as[0], bs[0], cs[0] is the 1st set, etc.
float a    , b    , c    ;

// Assigning values to sets: as[0] = ...; bs[0] = ..., cs[0] = ...;
                             as[1] = ...; bs[1] = ..., cs[1] = ...;
                             ......................................
                             ......................................

//  or initialize them directly in the previous declaration, e.g. 
//                           float as[] = {1,  4, -2,  3},
//                                 bs[] = {0,  5,  1, -1}, 
//                                 cs[] = {2, -4,  1,  2}; 

for (int i; i < 4; ++i)
{
    a = a[i];
    b = b[i];
    c = c[i];
    // Code (or a function call) for computing and printing result(s) from a, b, c
}