c++ - 使用 long double 但不使用 double 的未定义行为

标签 c++ c++11

学习 C++ Primer Plus。我正在做第 5 章的练习。让我先做第二个练习:

Redo Listing 5.4 using a type array object instead of a built-in array and type long double instead of long long.Find the value of 100! (factorial)

以及有问题的列表:

// formore -- more looping with for

#include <iostream>

int main()
{
    const int aSize = 100;
    long long factorials[aSize];

    factorials[1] = factorials[0] = 1LL;

    for (int i = 2; i < aSize; ++i)
        factorials[i] = i * factorials[i-1];
    for (int i = 0; i < aSize; ++i)
        std::cout << i << "! = " << factorials[i] << std::endl;

    return 0;
}

我按照练习说明重写了代码,结果如下:

// redo listing 5.4 using long double and arrays instead - find value of 100!

#include <iostream>
#include <array>

int main()
{
    int const ArSize = 100;
    std::array<long double, ArSize> factorials = {1.0L, 1.0L};

    for (int i = 2; i <= ArSize; ++i)
        factorials[i] = i * factorials[i-1];

    for (int i = 0; i <= ArSize; ++i)
        std::cout << i << "! = " << factorials[i] << std::endl;

    return 0;
}

当我尝试运行此代码时,出现未定义的行为。我很确定它与我使用的 long double 类型有关,因为当我将阶乘转换为 double 类型时,程序运行正常。究竟是什么原因造成的?

如果我问的是一个明显的问题,我深表歉意,它试图用谷歌搜索这个练习,但大多数人似乎都跳过它而只是做练习三......

编辑

将 ArSize 更改为:

const int ArSize = 101;

For 循环:

for (int i = 2; i < ArSize; ++i)
    factorials[i] = i * factorials[i-1];

for (int i = 0; i < ArSize; ++i)
    std::cout << i << "! = " << factorials[i] << std::endl;

我还在接受 UB;阶乘 [0] 到阶乘 [3] 显示为负数。 0

看这里:

enter image description here

我觉得这里有什么东西正在我头上。

最佳答案

你在这里分配越界,:

for (int i = 2; i <= ArSize; ++i)
    factorials[i] = i * factorials[i-1];

这里:

for (int i = 0; i <= ArSize; ++i)
    std::cout << i << "! = " << factorials[i] << std::endl;

那就是UB。 解决方案:不要越界访问数组。

注意:它与 double 或 std::array 无关。您更改了循环条件,引入了错误。

关于c++ - 使用 long double 但不使用 double 的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370016/

相关文章:

c++ - 转换运算符与删除的构造函数

c++ - 在 std::unordered_set 上:请求具有默认散列器的类型列表

c++ 将各种参数传递给父类构造函数(线程c++11)

c++ - 如何从 C stdio.h getline() 中替换/忽略无效的 Unicode/UTF8 字符?

c++ - 智能感知:错误 C2440: '=':无法从 'unsigned long (__stdcall *)(const char *)' 转换为 'IPAddr'

c++ - STL 容器大小要求

c++ - 创建构建框架以支持编译支持多平台的代码

c++ - 花 : How do I create a tuple of types from a variant?

c++ - FFMPEG 编译自定义

c++ - 调用 join 后删除 std::thread?