c 中的负对数结果
我需要在 C 中获取数字(0 到 1 之间)的自然对数。但是,如果结果为负数,C 中的自然对数函数会给出未定义的错误。
有什么办法解决这个问题吗?
编辑:抱歉,各位,我的代码翻转了输入和输出,我无法发现它,感谢您的快速帮助,为我明显的愚蠢感到抱歉!
I need to get the natural log of a number (between 0 and 1) in C. But the natural log function in C gives an undefined error if the result is negative.
What is the way around this?
EDIT: Sorry folks , my code had flipped the input and output , and I wasn't able to spot it , thanks for the quick help, sorry for my obvious stupidity!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,没有。如果输入为负数,它会给出错误(或者更确切地说,返回 NaN)。标准库
log
函数非常适合 0 到 1 之间的输入。No it doesn't. It gives an error (or rather, returns NaN) if the input is negative. The standard library
log
function works perfectly for inputs between zero and one.对于负数,对数没有实数解(在数学意义上使用
real
):负数的对数是一个复数值,不能用 Cdouble< 表示/代码>。因此标准库不会给出这样的结果:您需要找到一个复杂的数学库或编写自己的复杂日志函数。
编辑:大多数读者会注意到,我希望,我(可能是错误的!)假设OP意味着当输入为负数时发生错误,而不是结果!
Logarithms don't have a real solution (using
real
in its mathematical sense) for negative numbers: the log of a negative number is a complex value, which cannot be represented by a Cdouble
. So the standard library won't give a result for this: you'll need to find a complex maths library or write your own complex log function.Edit: most readers will have noticed, I hope, that I have (perhaps wrongly!) assumed that the OP means that the error occurs when the input is negative, not the result!
您的意思是结果是否为负,或者输入?
log()
应该不会有返回负结果的问题。显示您的代码和输出。如果您的意思是输入为负数,请在调用
log()
之前测试您的输入是否大于零。对于零或负数的对数没有合理的答案。Do you mean if the result is negative, or the input?
log()
should have no trouble returning negative results. Show your code and output.If you mean the input is negative, test that your input is greater than zero before calling
log()
. There's no sensible answer to the log of zero or negative numbers.我怀疑你的意思是编译程序时发生错误?然后确保
在编译时添加然后添加-lm。
I suspect you mean that the error happens when you compile the program? Then make sure that you add
and then add -lm when compiling.
您如何检测错误?
没有一个标准 C 库函数将
errno
设置为零,因此如果您想检测错误,则必须执行以下操作:如果您不将
errno
设置为0,您可以从之前的系统调用中获得任何剩余值。How do you detect the error?
None of the standard C library functions sets
errno
to zero, so if you want to detect an error, you have to do something like:If you don't set
errno
to 0, you may get any left-over value from any previous system call.