首页 > 解决方案 > (初学者)在 C 中找不到此代码的问题,它为浮点数返回奇怪的值(-nanloat)

问题描述

它只是一个超级基本的程序,可以找到二次函数的根。计算后,解决方案的输出显示“-nanloat”而不是实际答案。这是有问题的代码:

    /*If the polynomial has real solutions, calculate and print them */
    if (nRSolutions > 0){
        sol = ((-b + sqrt(pow(2.0,b) + 4 * a * c)) / (2.0 * a));
        printf("La solución a la ecuación es %float", sol);
        /*That means "the solution to the equation is (float)"*/
    }

    if (nRSolutions = 2){
        sol2 = ((-b - sqrt(pow(2.0,b) + 4 * a * c)) / (2.0 * a));
        printf("La segunda solución a la ecuación es %float", sol2);
        /*That means "the second solution to the equation is (float)"*/
    }

这是变量声明,以防万一这可能是问题的一部分,但我真的不认为就是这样。

/* d = discriminant value; sol = solution; sol2 = second solution*/
float a, b, c, d, sol, sol2; 
    int nRSolutions;
    nRSolutions = 0;

它们都是事后定义的。

标签: cfloating-point

解决方案


这是你的问题:

if (nRSolutions = 2){

您不是在比较而是在分配,并且由于您分配的值是非零的,因此条件将始终为真。你反而想要:

if (nRSolutions == 2){

推荐阅读