c++ - 为什么这个条件返回false,但是在main函数中却返回true?

标签 c++ logic

所以我正在研究 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。如果数字小于零或大于一,我希望它引发断言语句,例如,如果存储在数组特定索引中的值为 2 或 -0.3。

因此,我在主文件中对其进行了测试: “ma​​in.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;
}

所以,在“ma​​in.cpp”文件中,第一个值是 0.5,所以它检查为真,因为它介于 0 和 1 之间(含 0 和 1)。

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

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

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

编辑:如果我在 Linux Ubuntu 14.06 中编译它不会工作,但如果我在 OS X Yosemite 中编译它会工作。

最佳答案

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

像这样的线条

p[0] = 0.5;

也调用 double& operator[]。但是当第一次赋值时,结果已经取决于你内存中的内容。如果它小于 1+abs_error 一切都很好,如果不是,它会引发 assert(0)

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

关于c++ - 为什么这个条件返回false,但是在main函数中却返回true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35214740/

相关文章:

c++ - 禁用局部变量的未初始化警告

c++ - C++ 中的几何库

c++ - 为什么我的命令行参数处理会导致我的程序崩溃?

c++ - GTK3 OpenGL 视频渲染大部分为绿色 (YUV420P)

javascript - IP 地址验证,中间有适当的点

c++ - 以特定顺序扩展可变参数模板值的最有效方法是什么?

java - If 语句与 String.equals()

c++ - 逻辑设计模式

string - 通过递归生成集 - 语言和字符串(cs/logic)

R within() 操作顺序和逻辑