如何获得表示未定义值的c++
How to get represent undefined value C++?
我有计算两个斜率并比较它们的代码,如果它们相同,我得到它们的值。
但是,如果一个斜率未定义,则程序崩溃。我需要知道它们是否相同,即使它们没有定义。我不能使用任何其他的负整数或正整数,因为那会把我的代码弄得一团糟。
我更喜欢一个单词值,比如5/0 = undefined,但不确定如何做到这一点。
例如:#include <iostream>
using namespace std;
int r = 5/0;
int main()
{
// Instead of crashing, this should tell me this value is undefined somehow.
cout << r << endl;
return 0;
}
我该如何处理斜率完全垂直的情况?
您应该以始终定义的方式(例如角度)表示斜率。如果程序中的另一个步骤由于数学原因没有定义结果,则可以引发异常。
对于从向量x,y获取角度,你应该使用atan2 http://en.cppreference.com/w/cpp/numeric/math/atan2
double theta = atan2(y,x) ; // this is always fine
比较由向量x1,y1和x2,y2定义的两个角:
double th1 = atan2(y1,x1)
double th2 = atan2(y1,x1)
const double mypi=3.141592653589793238463;
double angleDiff = pi - abs(abs(th1 - th2) - pi);
if(angleDiff*10<=mypi){
cout << " angles are within 0.1 pi (that is 18 degr) <<endl;
}
还要记住,在比较浮点值时,不应该期望与完全匹配,除非有一些特殊情况。
我知道这个问题很老了,但由于我试图解决一个几乎相同的问题,我决定发布一个答案。
我建议一种方法是使用空指针来标识未定义的值。在我的情况下,使用角度是非常不准确的,因为我使用gmp (gnu多精度库),我需要从64位开始的巨大位大小的完美精度和爬升。
浮点数根本不合适。
正如我所看到的,你有两个选择:一个标志在检索斜率时单独测试,或者在检索斜率后测试。我找不到一个不抛出异常的替代方法
class line {
bool vertical;
bignum slope;
// one method two functions
bool is_vertical(){return vertical;}
bignum slope() {return slope}
//alternative method
bignum *slope() {if (vertical) return NULL; else return &slope}
}
大多数代码需要以不同的方式处理竖行,因此在if语句
中处理竖行并不是一项繁重的任务。if ((slope = line.slope())==NULL){//vertical
// do some vertical stuff
cout << "line is vertical";
} else {
// do some other line stuff with bignum *slope
cout "slope is " << *slope;
}
相关文章:
- 编译C++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- c++11评估顺序(未定义的行为)
- 使用mysql c++连接器的未定义引用
- 从python调用openMP共享库时,未定义opnMP函数
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- Cmake 链接问题:未定义对 Button::mousePressEvent(QGraphicsSceneMouseE
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 具有外部"c"和程序集的未定义函数
- 此增量后语句是否会导致未定义的行为?
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在C++中使用内联方法时出现未定义的符号错误
- 对 Scalar ::Scalar() 的未定义引用