在 c 中定义和使用负无穷大-ag捕鱼王app官网

在 c 中定义和使用负无穷大

作者:迹忆客 最近更新:2023/08/19 浏览次数:

本文讨论了在 c 中表示负无穷大的问题并列出了一些可能的ag捕鱼王app官网的解决方案。

c 使用 ieee-754 标准来表示浮点数。 浮点数据类型共有三种:float、double 和 long double。

所有这些变量类型都允许存储无法存储在 int 数据类型中的数值。

无穷大在 c 中写为 inf,结果是用一个正数值除以一个空值,或者计算出一个大于 64 位可以存储的数值。

无符号或正浮点无穷大值在各种 c 库(例如 cmath 和 limit)中定义,但 c 中没有负无穷大的标准。

由于 c 中没有表示负无穷大的标准方法,因此这里有几种在 c 中表示和使用负无穷大的可靠方法。


在 c 中使用 numeric_limits::infinity() 的负积

使用 c 中的 limits 库。

#include
#include
using namespace std;
int main()
{
    float f = numeric_limits<float>::infinity();
    float neginf= f*-1;
    cout << "the value of f is = " << f << endl;
    cout << "the value of neginf is = " << neginf << endl;
    cout << "the value of f   neginf is = " << f   neginf << endl;
    return 0;
}

在上面的代码片段中,limits 库中的 infinity 方法返回正无穷大的值。

语法如下。

numeric_limits::infinity()

在上面的定义中,尖括号之间的 t 代表模板类,在实际实现中,它被替换为要使用 numeric_limits 方法的数据类型。 在上面的代码片段中,使用了float数据类型,但也可以类似地使用double。

但是,infinity() 方法仅对非整数数据类型有效,因为 int 和 bool 等整数数据类型本质上是有限的。

上述代码的输出如下。

the value of f is = inf
the value of neginf is = -inf
the value of f   neginf is = nan

如上例所示,使用 infinity() 方法,将正无穷大的值赋给 float 类型变量 f。 然后使用一种非常简单直观的方法,即将 f 乘以 -1,并将结果存储在名为 neginf 的变量中,从而将负无穷大的值存储在 neginf 中。

如上面的输出所示,此有效方法将负无穷大值分配给变量。 为了进一步测试这个方法,将f和neginf相加,结果返回nan,它代表not-a-number,表示一个无法计算的值。

此结果与无穷大值的 ieee-754 规则一致,因此计算安全。


使用 cmath 库中的 infinity 定义

cmath 库是另一个 c 库,具有许多有用的方法和函数来处理常见的数学运算和转换。

该库还包含无穷大值的定义,该定义名为 infinity,其使用方式与 numeric_limits::infinity() 大致相同,并且可以直接分配给 float 和 double 数据类型。

使用与上一个示例相同的方法,将无符号或正无穷大的值乘以负值将返回负无穷大值。

#include
#include
using namespace std;
int main()
{
    long double f = infinity;
    long double neginf= f*-1;
    cout << "the value of f is = " << f << endl;
    cout << "the value of neginf is = " << neginf << endl;
    cout << "the value of f   neginf is = " << f   neginf << endl;
    return 0;
}

上述代码的输出如下。

the value of f is = inf
the value of neginf is = -inf
the value of f   neginf is = nan

可以看出,两种方法产生相同的输出,并且都可以安全地用于在 c 中实现负无穷大。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

arduino 中停止循环

发布时间:2024/03/13 浏览次数:444 分类:c

可以使用 exit(0),无限循环和 sleep_n0m1 库在 arduino 中停止循环。

arduino 复位

发布时间:2024/03/13 浏览次数:315 分类:c

可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。

发布时间:2024/03/13 浏览次数:181 分类:c

可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。

arduino 串口打印多个变量

发布时间:2024/03/13 浏览次数:381 分类:c

可以使用 serial.print()和 serial.println()函数在串口监视器上显示变量值。

arduino if 语句

发布时间:2024/03/13 浏览次数:123 分类:c

可以使用 if 语句检查 arduino 中的不同条件。

arduino icsp

发布时间:2024/03/13 浏览次数:214 分类:c

icsp 引脚用于两个 arduino 之间的通信以及对 arduino 引导加载程序进行编程。

发布时间:2024/03/13 浏览次数:151 分类:c

可以使用 arduino 中的循环制作计数器。

使用 c 编程 arduino

发布时间:2024/03/13 浏览次数:127 分类:c

本教程将讨论使用 arduino ide 在 c 中对 arduino 进行编程。

arduino 中的子程序

发布时间:2024/03/13 浏览次数:168 分类:c

可以通过在 arduino 中声明函数来处理子程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图