gpt4 book ai didi

c - 程序返回错误答案和 "-nan(ind)"。我做错了什么?

转载 作者:行者123 更新时间:2023-11-30 19:06:55 28 4
gpt4 key购买 nike

这是我的代码

#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但我得到的输出是“奇异解是 -nan(ind)”这是什么意思?我该如何修复它?

最佳答案

变量不会追溯初始化或重新计算。

例如,与

float disc = b*b - 4 * a*c;

初始化等于0 * 0 - 4 * 0 * 0,即0

定义变量,然后读取输入,然后进行计算。

关于c - 程序返回错误答案和 "-nan(ind)"。我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47389791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com