我编写了以下代码来计算二次方程的根:

int quadroots(int *ap, int *bp, int *cp,int *root1p, int *root2p, int *dp);
int main (void) {
    int ap,bp,cp;
    int dp, root1p, root2p;
    quadroots(&ap, &bp, &cp, &root1p, &root2p, &dp);
    printf("The solutions are: %f, %f", root1p, root2p);
    }

int quadroots(int *ap, int *bp, int *cp,int *root1p, int *root2p, int *dp){
    int a, b, c, d, root1, root2;
    printf("Enter a, b, c \n");
    scanf("%d, %d, %d", &a, &b, &c);
    if (a==0) {
        printf ("The system is linear. The roots cannot be computed using this program: a cannot be 0. Please recompile");

    return 0;
    }
    int b_sqared = b*b;

    d = b_sqared - (4 * a * c);

    if (d<0) {

    d=-d;
    printf("The roots of this equation are the complex numbers: \n");
    printf("%.3f+%.3fi", ((-b) / (2*a)), (sqrt(d) / (2 * a)));
    printf(", %.3f%.3fi", (-b / (2*a)), (-sqrt(d) / (2*a)));

    }

    else if (d==0) {
        printf("The root of this equation are real and equal. \n");

        root1= (-d / (2*a));
        printf("The roots of this equation are: %.3f, %.3f", root1, root1);
        }

    else {

        printf ("The roots of the quadratic equation are real numbers. \n");
        root1 = (-b + sqrt(d)) /  (2*a);
        root2 = (-b - sqrt(d)) / (2*a);

        printf("Roots of the quadratic equation are the real numbers %.3f, %.3f", root1,root2);

        }

    return 0;
    *root1p=root1;
    *root2p=root2;
}


这是基于我之前编写的有效代码,但那时我还没有使用函数。

现在,它可以编译并运行良好(即,它接受数字并执行计算),但是打印出来的答案是完全错误的。

例如。对于输入“ 1 5 6”(与等式x ^ 2 + 5x + 6对应,应打印出“根为实数。
根是实数6和1“
因为这些是等式的根。但是,事实并非如此。打印出的是一些非常大的数字(输入a,b,c
1 5 6
该方程式的根是复数:
-2719010580126301300000000000.000 + 0.000i,-2719010580126301300000000000.0000.000i解决方案是:0.000000,0.000000)

任何帮助将非常感激。

非常感谢你!最好。

最佳答案

printf("%.3f+%.3fi", ((-b) / (2*a)), (sqrt(d) / (2 * a)));


您在((-b) / (2*a))中使用整数除法,因此对于某些数字,您将获得不正确的值。

您可以使用。

printf("%.3f+%.3fi", ((-b) / (2.0*a)), (sqrt(d) / (2 * a)));


迫使转换为除法前的两倍。您需要对代码中两个整数之间的所有除法进行此操作。

关于c - C程序无法打印出正确的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41036130/

10-11 15:55