为什么这个条件返回 false,但在主函数中它返回 true
Why does this condition return false, but in the main function it returns true?
所以我正在研究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}
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数