为什么这个条件返回 false,但在主函数中它返回 true

Why does this condition return false, but in the main function it returns true?

本文关键字:返回 函数 true 条件 false 为什么      更新时间:2023-10-16

所以我正在研究C++模板,我有这个模板类,">Test.h":

#ifndef TEST_H
#define TEST_H
#include <cassert>
#include <iostream>
#include <cmath>    // for std::abs
template<unsigned int DIM> class Test
{
private:
    double abs_error = 1e-6;
    double mData[DIM];
public:
    double& operator[](int index)
    {
        // To check that the input index is a valid one
        assert(index < DIM);
        assert(index > -1);
        // Condition that checks for values between 0 and 1 inclusive
        if (mData[index] >= 0.0 && mData[index] <= 1.0)
        {
            return mData[index];
        }
        // Values less than zero
        else if (std::abs(mData[index]) <= abs_error && mData[index] <= 0.0)
        {
            return mData[index] = 0;
        }
        // Values more than one
        else if (mData[index] >= 1.0 && std::abs(mData[index] - 1.0) <= abs_error)
        {
            std::cout << "You used this condition." << std::endl;
            return mData[index] = 1;
        }
        // For every other possible value
        else
        {
            assert(0);
        }
        return mData[index];
    }

};

#endif //TEST_H

从技术上检查分配给数组中特定索引的值。我希望它做的是,如果数字介于 0 和 0.000001 之间,我希望它为该特定索引返回 0。如果数字介于 1 和 1.000001 之间,我希望它将分配给该特定索引的值更改为 1。如果数字小于零或大于 1,我希望它引发一个断言语句,例如,如果存储在数组的特定索引中的值为 2 或 -0.3。

因此,我在主文件中对其进行了测试:">主.cpp">

#include <iostream>
#include <cmath>
#include "Test.h"
int main()
{
    Test<6> p;
    p[0] = 0.5;
    std::cout << "p[0]: " << p[0] << std::endl;
    p[1] = -1e-7;
    std::cout << "p[1]: " << p[1] << std::end;
    // Comment the following two lines and check the test statement
    p[2] = 1+1e-8;
    std::cout << "p[2]: " << p[2] << std::endl;
    // This code tests the same condition as in Test.h for 
    // values more than one
    bool foo = 1+1e-8 >= 1.0 && std::abs(1+1e-8 - 1.0) <= 1e-6;
    std::cout << "foo (should return 1): " << foo << std::endl;
    return 0;
}

因此,在">main.cpp"文件中,第一个值为 0.5,因此它检查为 true,因为它介于 0 和 1 之间(包括 0 和 1(。

下一个也返回 true,因为它介于 0 和 0.000001 之间(包括 0 和 0.000001(,因此它被分配为 0 并且应该在屏幕上打印。

但是

第三个提出了断言,但是如果您注释掉该部分并将测试语句保留在文件底部,它将返回true,即使它是相同的逻辑条件。

我的问题是,我在这里做错了什么?

编辑:如果我在Linux Ubuntu 14.06中编译,它将不起作用,但是如果我在OS X Yosemite中编译,它可以工作。

问题可能是您没有初始化值。

像这样的台词

p[0] = 0.5;

也叫double& operator[]。但是,当第一次分配一个值时,结果已经取决于内存中的任何内容。如果它小于1+abs_error则一切正常,如果不是,则提高assert(0)

所以你应该用至少不会引发断言的东西来初始化你的数组,例如{0}