如何获得表示未定义值的c++

How to get represent undefined value C++?

本文关键字:c++ 未定义 何获得 表示      更新时间:2023-10-16

我有计算两个斜率并比较它们的代码,如果它们相同,我得到它们的值。

但是,如果一个斜率未定义,则程序崩溃。我需要知道它们是否相同,即使它们没有定义。我不能使用任何其他的负整数或正整数,因为那会把我的代码弄得一团糟。

我更喜欢一个单词值,比如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;
}