C语言解x^3➕px➕q=0遇到的问题

输入的两个正整数(1,3)为什么出现这样奇怪的结果
用的公式法求的是实根
图2附上求根公式

img

img

对于标准库函数pow(base, exp),当base是负数并且指数不是整数时,会出现域错误。所以当你求三次方根时,你需要判断base的符号,如果是负数,你需要把它变成正数来计算三次方根,然后再把结果变成负数。

至于为什么打印结果是-1.#IO,pow函数由于域错误返回结果是NaN(Not at Number),Windows系统显示NaN为-1.#IND ("IND" for "indeterminate"),当按%.3lf格式四舍五入并保留三位小数输出时,'D'>'5',进一位,'N'就变成了'O',于是就得到-1.#IO

https://en.cppreference.com/w/c/numeric/math/pow

If base is finite and negative and exponent is finite and non-integer, a domain error occurs and a range error may occur.

https://stackoverflow.com/questions/347920/what-do-1-inf00-1-ind00-and-1-ind-mean


#include<stdio.h>
#include<math.h>                                             
int main()
{
  int p, q;
  double x, k, m, a, b;
  scanf("%d%d", &p, &q);
  m = pow(q / 2.0, 2) + pow(p / 3.0, 3);
  k = sqrt(m);
  a = -q / 2. + k;
  b = -q / 2.0 - k;
  if (a > 0)
    a = pow(fabs(a), 1.0 / 3.0);
  else
    a = -pow(fabs(a), 1.0 / 3.0);
  if (b > 0)
    b = pow(fabs(b), 1.0 / 3.0);
  else
    b = -pow(fabs(b), 1.0 / 3.0);
  x = a + b;
  printf("%.7f\n", x);
  printf("%.7f\n", x*x*x+p*x+q);//检验
  return 0;
}



scanf("%d%d",&p,&q)这样写试试看scanf("%d %d",&p,&q

有些三次方程确实是没有解的,答案奇怪在情理之中

找到解决方法了,把pow换成了cbrt()就可以了 但实在是不清楚为什么