编写一个C++风格的程序,建立一个被称为sroot()的函数,返回其参数的二次方根。重载函数sroot()3次,让它返回整数、长整数与双精度数的二次方根(计算二次方根时,可以使用标准库函数sqrt())
时间: 2024-09-19 16:03:31 浏览: 51
在C++中,你可以通过模板和重载(overload)函数来实现这个需求,这里是一个简单的例子:
```cpp
#include <cmath> // 引入包含平方根函数的头文件
// 定义一个通用模板函数,用于获取任意类型数值的平方根
template <typename T>
T sroot(T num) {
if constexpr (std::is_integral<T>::value) { // 判断是否为整型
return static_cast<T>(std::sqrt(static_cast<double>(num))); // 避免直接对整数开平方可能导致的整数溢出
} else if constexpr (std::is_floating_point<T>::value) { // 判断是否为浮点型
return std::sqrt(num); // 直接使用sqrt函数,因为浮点数不会有溢出问题
} else {
throw std::invalid_argument("Unsupported data type for square root"); // 对于非数值类型抛出异常
}
}
// 重载函数,分别处理整数、长整数和双精度数的情况
int sroot(int num) {
return static_cast<int>(std::sqrt(num));
}
long long sroot(long long num) {
return static_cast<long long>(std::sqrt(num));
}
double sroot(double num) {
return std::sqrt(num);
}
int main() {
int i = 9;
long long l = 1000000000000LL;
double d = 4.0;
std::cout << "Square root of " << i << ": " << sroot(i) << "\n";
std::cout << "Square root of " << l << ": " << sroot(l) << "\n";
std::cout << "Square root of " << d << ": " << sroot(d) << "\n";
return 0;
}
```
在这个例子中,`sroot`函数首先检查传入类型的特性,然后选择合适的计算方式。在`main`函数中展示了如何调用这些重载版本。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)