编程 returns 个错误答案和“-nan(ind)”。我做错了什么?
Program returns incorrect answer and "-nan(ind)". What did I do wrong?
这是我的代码
#include <stdio.h>
#include <math.h>
void main()
{
float a = 0, b = 0, c = 0;
float disc = b*b - 4 * a*c;
float sing = -b / (2 * a);
float lin = -c / b;
float quad1 = (-b + (disc)) / (2 * a);
float quad2 = (-b - (disc)) / (2 * a);
printf_s("Please enter the coefficients a, b, and c\n");
scanf_s("%g %g %g", &a, &b, &c);
if (a == 0)
{
if (b == 0)
{
if (c == 0)
{
printf_s("There are infinite solutions\n");
}
else
{
printf_s("There is no solution\n");
}
}
else
{
printf_s("The singular solution is %g\n", lin);
}
}
else
{
if (disc < 0)
{
printf_s("There is no real solution\n");
}
else
{
if (disc == 0)
{
printf_s("The singular solution is %g\n", sing);
}
else
{
printf_s("The solutions are x1 = %g and x2 = %g\n", quad1, quad2);
}
}
}
}
我正在尝试构建一个二次公式计算器。当我插入 a = 2、b = 1 和 c = -21 时,我希望收到 x = 3 和 x = -3.5
但是我得到了输出 "The singular solution is -nan(ind)"
这是什么意思?我该如何解决?
您正在计算 disc
before 输入的值。更改顺序。
这也适用于 sing
、lin
、quad1
和 quad2
。
float a, b, c;
printf_s("Please enter the coefficients a, b, and c\n");
scanf_s("%g %g %g", &a, &b, &c);
float disc = b*b - 4 * a*c;
float sing = -b / (2 * a);
float lin = -c / b;
float quad1 = (-b + (disc)) / (2 * a);
float quad2 = (-b - (disc)) / (2 * a);
查看这些行
float sing = -b / (2 * a);
float lin = -c / b;
在这里,您正在尝试除以零,这没有意义。
您可能需要在读取用户的值后移动操作。
变量未初始化或追溯重新计算。
例如,与
float disc = b*b - 4 * a*c;
初始化等于0 * 0 - 4 * 0 * 0
,即0
。
定义变量,然后读取输入,然后进行计算。
这是我的代码
#include <stdio.h>
#include <math.h>
void main()
{
float a = 0, b = 0, c = 0;
float disc = b*b - 4 * a*c;
float sing = -b / (2 * a);
float lin = -c / b;
float quad1 = (-b + (disc)) / (2 * a);
float quad2 = (-b - (disc)) / (2 * a);
printf_s("Please enter the coefficients a, b, and c\n");
scanf_s("%g %g %g", &a, &b, &c);
if (a == 0)
{
if (b == 0)
{
if (c == 0)
{
printf_s("There are infinite solutions\n");
}
else
{
printf_s("There is no solution\n");
}
}
else
{
printf_s("The singular solution is %g\n", lin);
}
}
else
{
if (disc < 0)
{
printf_s("There is no real solution\n");
}
else
{
if (disc == 0)
{
printf_s("The singular solution is %g\n", sing);
}
else
{
printf_s("The solutions are x1 = %g and x2 = %g\n", quad1, quad2);
}
}
}
}
我正在尝试构建一个二次公式计算器。当我插入 a = 2、b = 1 和 c = -21 时,我希望收到 x = 3 和 x = -3.5 但是我得到了输出 "The singular solution is -nan(ind)" 这是什么意思?我该如何解决?
您正在计算 disc
before 输入的值。更改顺序。
这也适用于 sing
、lin
、quad1
和 quad2
。
float a, b, c;
printf_s("Please enter the coefficients a, b, and c\n");
scanf_s("%g %g %g", &a, &b, &c);
float disc = b*b - 4 * a*c;
float sing = -b / (2 * a);
float lin = -c / b;
float quad1 = (-b + (disc)) / (2 * a);
float quad2 = (-b - (disc)) / (2 * a);
查看这些行
float sing = -b / (2 * a);
float lin = -c / b;
在这里,您正在尝试除以零,这没有意义。
您可能需要在读取用户的值后移动操作。
变量未初始化或追溯重新计算。
例如,与
float disc = b*b - 4 * a*c;
初始化等于0 * 0 - 4 * 0 * 0
,即0
。
定义变量,然后读取输入,然后进行计算。