在使用常用的数学函数exp() log()时,如何防止溢出?

Microsoft 365 登录 📅 2026-01-29 19:07:24 ✍️ admin 👁️ 6204 ❤️ 991
在使用常用的数学函数exp() log()时,如何防止溢出?

预先检查溢出的最好方法是在逐个案例的基础上智能地进行检查。

使用您的对数和指数知识,您应该能够使用像INT_MAX这样的属性来识别潜在的溢出:检查这些C++ Limitations

我给出了一个粗略的c++执行示例,假设您事先知道要遵循的限制。

代码语言:javascript复制#include

// nTh root calculator

bool is_exp_overflow(int input_val, int exponent)

{

my_max = pow(INT_MAX, (1/exponent);

if (input_val > my_max)

{

return true;

}

else

return false;

}

void runExp(int my_input, int my_exp)

{

// Do maths

}

int main()

{

int my_input = 0;

int my_exp = 0;

std::cout << "Enter test value\n";

std::cin >> my_input;

std::cout << "Enter test exponent\n";

std::cin >> my_exp;

bool exp_unsafe = 1;

exp_unsafe = is_exp_overflow(my_input, my_exp);

if (!exp_unsafe)

runExp(my_input, my_exp);

else

std::cout << "Code is unsafe\n";

return 0;

}如果您希望在事后捕获错误,请检查errno in range。

相关推荐

喜马拉雅
体育365

喜马拉雅

📅 09-17 👁️ 4031