C代码的输出
为什么输出给出 3 ,期望 -3 。如何在c中处理这样的预处理?
#include<stdio.h>
#include<math.h>
#define sq(x) ((x<0)?sqrt(-x):sqrt(x))
int main()
{
int x;
x=sq(-9);
printf("%d\n",x);
return 0;
}
Why output is giving 3 , expecting -3. How to handle such preprocessing in c?
#include<stdio.h>
#include<math.h>
#define sq(x) ((x<0)?sqrt(-x):sqrt(x))
int main()
{
int x;
x=sq(-9);
printf("%d\n",x);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为你的#define“sq”检查它是否是负数,并在计算平方根之前将其转换为正数
,它执行 sqrt(-x) ,即 sqrt(-(-9)) (取负数的负数是积极)
所以它在做 sqrt(9)
because your # define "sq" checks if its a negative number and turns it into a positive number before calculating a square root
its doing sqrt(-x) which is sqrt(-(-9)) ( taking the negative of a negative is the positive)
so its doing sqrt(9)
您有这样的定义:
由于您传递的是 -9,所以
x<0
为 true,因此它正在执行sqrt(9)
,即 3。然后打印 3 。
You have this define:
Since you're passing -9,
x<0
is true, so it's doingsqrt(9)
, which is 3.You then print the 3.
我认为代码完全按照它所告诉的那样执行。
sq(x)
首先测试x
x
0
- 在您的情况下,这是正确的,因此sq(x)
调用sqrt(-(-9))
- 这是 3.尝试的解决方案是
(x < 0) 吗? -sqrt(-x) :sqrt(x)
,它将返回负x
的负根(我对你的意图的最佳解释)。The code is doing exactly what it's being told, I think.
sq(x)
tests first forx < 0
- in your case, this is true, sosq(x)
callssqrt(-(-9))
- which is 3.An attempted solution is
(x < 0) ? -sqrt(-x) : sqrt(x)
, which will return negative roots for negativex
(my best interpretation of your intent).等等,等等,等等。
我们是否试图打破数学的基本规则?
-9 的平方根是 3 i。
那是因为 (-3)^2 是 9。负数有“虚数”平方根。 sqrt(-1) 是i。不是-1。 (-1)^2 是 1。
Wait, wait, wait.
Are we trying to break the basic rules of Math here?
The square root of -9 is 3 i.
That's because (-3)^2 is 9. Negative numbers have 'imaginary' square roots. sqrt(-1) is i. Not -1. (-1)^2 is 1.
如果您期望
-3
,那么您的意思可能是但为什么您会期望负数的负平方根超出了我的范围。
If you expect
-3
, then you probably meantbut why would you expect negative square root of negative number is beyond me.