[英]errno value is not updated (c++)
我是編碼新手(目前正在學習c ++,並且我對C有所了解)...
正在閱讀math.h中的函數並閱讀errno ...
根據我提到的網站:
域錯誤(輸入參數超出了數學定義操作的范圍,例如std :: sqrt(-1),std :: log(-1)或std :: acos(2))。 如果MATH_ERRNO位置1,則將EDOM分配給errno。 如果MATH_ERREXCEPT位置1,則FE_INVALID升高。
所以我試着用這種知識編寫一個小程序...
#include <iostream>
#include <cerrno>
#include <cmath>
using namespace std;
int main (void)
{
errno = 0;
cout<<"\nWhat I get :-\n";
cout << "log(-3) = " << log(-3) << "\n";
//shouldn't it do (errno = EDOM) in the above step?
cout << "errno = " << errno << "\n";
cout << strerror(errno) << "\n";
errno = EDOM;
cout<<"\nWhat I want :-\n";
cout << "log(-3) = " << log(-3) << "\n";
cout << "errno = " << errno << "\n";
cout << strerror(errno) << "\n\n";
return(0);
}
在輸出中我看到即使-3不在log()的域中,我的第一個塊中errno也沒有更新為EDOM ...
輸出: -
What I get :-
log(-3) = nan
errno = 0
Undefined error: 0
What I want :-
log(-3) = nan
errno = 33
Numerical argument out of domain
我不明白我在這里缺少什么...請幫助...
我正在Mac上的Apple LLVM版本7.3.0(clang-703.0.31)上編譯代碼。
#define MATH_ERRNO 1
是非法的。 您不應重新定義標准庫符號。 標准已將MATH_ERRNO定義為1。
您無法設置實現如何處理錯誤(除了特定於編譯器的開關。請閱讀您的編譯器的文檔)。 您只能檢查它:
if (math_errhandling & MATH_ERRNO)
std::cout << "Error reporting uses errno\n";
else
std::cout << "Error reporting does not use errno\n";
if (math_errhandling & MATH_ERREXCEPT)
std::cout << "Error reporting uses floating-point exceptions\n";
else
std::cout << "Error reporting does not use floating-point exceptions\n";
對於clang,要使用/不使用errno
相關標志是-fmath-errno
/ -fmath-no-errno
errno
。
從有關已報告錯誤的討論來看,標准庫的Mac實現似乎根本不使用errno
。 因此,如果您想將其用於錯誤報告,那將很不走運。
您可以在以下位置找到完整的數學錯誤處理示例(用C語言編寫): http ://www.cplusplus.com/reference/cmath/math_errhandling/有關該站點的完整示例:
#include <stdio.h> /* printf */
#include <math.h> /* math_errhandling */
#include <errno.h> /* errno, EDOM */
#include <fenv.h> /* feclearexcept, fetestexcept, FE_ALL_EXCEPT, FE_INVALID */
#pragma STDC FENV_ACCESS on
int main () {
errno = 0;
if (math_errhandling & MATH_ERREXCEPT) feclearexcept(FE_ALL_EXCEPT);
printf ("Error handling: %d",math_errhandling);
sqrt (-1);
if (math_errhandling & MATH_ERRNO) {
if (errno==EDOM) printf("errno set to EDOM\n");
}
if (math_errhandling &MATH_ERREXCEPT) {
if (fetestexcept(FE_INVALID)) printf("FE_INVALID raised\n");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.