【问题标题】:implementation of isnan() functionisnan() 函数的实现
【发布时间】:2013-05-07 12:54:39
【问题描述】:

我是 C++ 编程的初学者,我的任务是在 C++ 中实现定点数学运算。在这里,我正在尝试实现一个函数 isnan() 如果数字不是数字则返回 true,否则将返回 false。

测试文件

#include "fixed_point_header.h"
int main()
{
fp::fixed_point<long long int, 63> a=fp::fixed_point<long long int, 63>::positive_infinity(); // will assign positive infinity value to a from an function from header 
fp::fixed_point<long long int, 63> b=fp::fixed_point<long long int, 63>::negative_infinity(); // will assign positive infinity value to b from an function from header 
float nan=fp::fixed_point<long long int, 63>::isnan(a,b);
printf( "fixed point nan value  == %f\n", float (nan));
} 

在标题中,如果添加了正无穷和负无穷值,我想做一些类似于下面显示的代码,isnan 函数应该返回 1,否则返回 0。

头文件

#include fixed_point_header
static fp::fixed_point<FP, I, F> isnan (fp::fixed_point<FP, I, F> x,fp::fixed_point<FP, I, F> y){
/*if ( x + y ) happens, ie. x and y are infinities
      {
 should return 1; }
       else {
 should return 0; }
      } */

谁能告诉我如何进行?或者如何解决这个范式

【问题讨论】:

  • @Mike Seymouroh 是的,isnan 函数将接受一个参数并根据它是否为 nan 返回 1 或 0。所以首先我需要定义nan的?
  • 是的,您需要定义一个值来表示nan。顺便说一句,当我将其扩展为答案时,我删除了我的评论。

标签: c++ nan fixed-point infinity


【解决方案1】:

我正在尝试实现一个函数 isnan(),如果数字不是数字则返回 true,否则将返回 false。

这很简单;定义一个保留值来表示nan(就像你对无穷大一样),并与之比较:

bool isnan(fixed_point x) {
    return x == fixed_point::nan();
}

如果添加正负无穷大值,我想做一些类似于下面显示的代码,isnan 函数应该返回 1 else 0

加法运算符有责任检查输入并在适当时返回nan

fixed_point operator+(fixed_point x, fixed_point y) {
    if (x == fixed_point::nan() || y == fixed_point::nan()) {
        return nan;
    }
    if (x == fixed_point::positive_infinity()) {
        return y == fixed_point::negative_infinity() ? fixed_point::nan() : x;
    }
    // and so on
}

那么main 中的测试变为:

bool nan = fixed_point::isnan(a+b);

【讨论】:

  • 谢谢回复,我有疑问,调用bool nan = fixed_point::isnan(a+b);会调用哪个函数?你能解释一下当bool nan = fixed_point::isnan(a+b);被调用时如何编码流程吗?
  • @Dr7:首先它会调用operator+进行加法;然后它会调用isnan检查结果是否为数字。
猜你喜欢
  • 2013-04-27
  • 2013-02-17
  • 1970-01-01
  • 2014-07-27
  • 2016-03-06
  • 2016-06-23
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
相关资源
最近更新 更多