【问题标题】:Why does this condition return false, but in the main function it returns true?为什么这个条件返回false,但在main函数中返回true?
【发布时间】:2016-02-05 01:15:34
【问题描述】:

所以我正在研究 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,所以它检查 true,因为它介于 0 和 1 之间。

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

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

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

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

【问题讨论】:

  • 您的运算符根本不返回布尔值。它返回一个double&amp;。
  • 似乎在这里工作Demo。
  • p.mData的条目是否初始化?
  • @paddy 我不希望它返回一个布尔值,我只希望它根据情况分配 0 或 1。布尔测试语句只是为了检查“else if”条件是否确实返回 true。
  • @NickyC 不,条目未初始化。

标签: c++ logic


【解决方案1】:

问题可能是你没有初始化这些值。

类似的行

p[0] = 0.5;

也可以拨打double&amp; operator[]。但是当第一次分配一个值时,结果已经取决于你记忆中的任何东西。如果它小于1+abs_error,一切都很好,如果不是,它会提高assert(0)。

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

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 2018-08-27
    • 2018-11-09
    • 2018-01-28
    • 1970-01-01
    • 2013-09-18
    • 2015-10-03
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多