【问题标题】:Need to write the contents of the function [closed]需要写函数的内容[关闭]
【发布时间】:2014-03-23 11:28:51
【问题描述】:

有源代码。函数func的内容未知:

#include <stdio.h>
#include <math.h>
float func (void)
{
  // Black box
}

int main (void)
{
  float f1, f2;
  int r1, r2;

  f1 = 5.0f;
  f2 = func();

  r1 = (f1 > f2);
  r2 = (f1 <= f2);

  printf ("r1=%d r2=%d\n", r1, r2); 
  return 0;
}

需要写函数func的内容,打印出消息:

r1=0 r2=0

答案:

返回 pow(-5.0, 0.5);

返回 0.0/0.0;

不明白,为什么会这样?

【问题讨论】:

  • 这是某种脑筋急转弯吗?
  • 你知道C语言中0.0/0.0是什么意思吗?
  • @TunZarniKyaw: Both 如果f2NaNf1 &gt; f2f1 &lt;= f2 可能为假。
  • 只需输入return NAN;NAN 是在 math.h 标头中定义的宏。

标签: c


【解决方案1】:

关于答案

return 0.0/0.0;

它将返回NaN。现在在这种情况下,r1r2 都变为 0

如果你返回

return pow(-5.0, 0.5); 

负数的平方根是虚数,因此不能表示为实数浮点数,因此用 NaN 表示。在这种情况下,r1r2 都是 0
你的函数看起来像:

float func (void)
{
     return 0.0/0.0 // return pow(-5.0, 0.5);
}  

另一种选择是,只返回 NaN。 (包括&lt;math.h&gt;)。

float func (void)
{
    return NAN;
}

【讨论】:

  • pow(-5.0, 0.5) 返回NaNdouble pow(double, double) 不返回复数。
  • @MartinR;我刚在 wiki 上读到这个:en.wikipedia.org/wiki/NaN :)
  • 来自“man pow”:pow(x, y) 返回一个 NaN 并引发有限 x
  • 宏是NAN,而不是NaN
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2016-03-29
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-06
相关资源
最近更新 更多