1

我编写了一个小的 c 代码来查找数字的 sqrt。而且我希望程序甚至可以找到负数的 sqrt。我遇到了 complex.h 和几个函数来执行复杂的算术。我已经使用了它们,并且在编译时收到了一些警告消息。代码没有正确计算正数和负数的平方根。

1) printf 和 scanf 用于打印和输入复数的正确格式说明符是什么?请让我知道我到底哪里出错了。我使用的是 gcc 编译器,操作系统是 Ubuntu 12.04 LTS。我附上了代码和输出。

    #include <stdio.h>
    #include <math.h>
    #include <complex.h>


    int main()
    {
      float complex var,op;
      printf(" Enter the number : " );
      scanf("%lf",&var);
      op=csqrt(var);
      printf("%lf \n",op);
    }

    o/p Enter the number : 4
        0.011604
    Another o/p Enter the number : -4
        -0.011604
4

3 回答 3

2

从 C99 开始:

6.2.5/13 类型

每个复杂类型具有与恰好包含对应实类型的两个元素的数组类型相同的表示和对齐要求;第一个元素等于复数的实部,第二个元素等于复数的虚部。

因此,作为一种可能性,您可以使用:

scanf("%f %f",&var[0], &var[1]);

读入一个float complex类型,用空格分隔实部和虚部。

于 2013-06-01T15:19:12.737 回答
1

printf并且scanf没有对复数的本机支持,但这没关系;你可以很容易地编写格式:

scanf( "%f %fi", &re, &im );

nowreim包含实部和虚部(虽然它不接受+or之后的空格-,所以3 + 2i会被拒绝,但是3 +2iand3+2i很好。

打印也是如此。

printf( "%f%+fi", re, im );

将以3+2i表格形式打印变量。

最后,虽然它似乎不是您问题的直接部分,但负数的平方根只是正值的平方根乘以i.

于 2013-06-01T15:21:25.087 回答
1

要找到负数的平方根,您可以使用以下代码,

  printf(" Enter the number : " );
  scanf("%lf",&var);
  if(var < 0)
  {
     op=csqrt(-var);
     printf("The square root is %lfi \n",op);
  }
  else
  {
     op=csqrt(var);
     printf("The square root is %lf \n",op);
  }
于 2013-06-01T15:15:35.997 回答