编写一个c++风格的程序,建立一个被称为sroot()的函数,返回其参数的二次方根。重载sroot()函数3次,让它返回键盘输入的整数、长整数与双精度数的二次方根(计算二次方根,可使用标准库函数sqr
时间: 2023-04-27 21:06:28 浏览: 421
编写一个C++风格的程序,建立一个名为sroot()的函数,返回其参数的二次方根。重载sroot()函数3次,让它返回键盘输入的整数、长整数与双精度数的二次方根(计算二次方根,可使用标准库函数sqrt())。以下是示例代码:
#include <iostream>
#include <cmath>
using namespace std;
int sroot(int x) {
return sqrt(x);
}
long sroot(long x) {
return sqrt(x);
}
double sroot(double x) {
return sqrt(x);
}
int main() {
int a;
long b;
double c;
cout << "请输入一个整数:";
cin >> a;
cout << "该整数的二次方根为:" << sroot(a) << endl;
cout << "请输入一个长整数:";
cin >> b;
cout << "该长整数的二次方根为:" << sroot(b) << endl;
cout << "请输入一个双精度数:";
cin >> c;
cout << "该双精度数的二次方根为:" << sroot(c) << endl;
return 0;
}
相关问题
编写一个C++风格的程序,建立一个被称为sroot()的函数,返回其参数的二次方根。重载函数sroot()3次,让它返回整数、长整数与双精度数的二次方根(计算二次方根时,可以使用标准库函数sqrt())。
好的,这是一个关于编程的问题。可以直接回答。
这里是一个C风格的程序,其中sroot()函数返回其参数的二次方根:
```
#include <stdio.h>
#include <math.h>
float sroot(float x) {
return sqrt(x);
}
int main() {
float x = 4.0;
printf("The square root of %f is %f\n", x, sroot(x));
return 0;
}
```
现在让我们重载sroot()函数,让它返回整数、长整数和双精度数的二次方根:
```
#include <stdio.h>
#include <math.h>
int sroot(int x) {
return (int)sqrt(x);
}
long int sroot(long int x) {
return (long int)sqrt((double)x);
}
double sroot(double x) {
return sqrt(x);
}
int main() {
int i = 4;
long int l = 9;
double d = 16.0;
printf("The square root of %d is %d\n", i, sroot(i));
printf("The square root of %ld is %ld\n", l, sroot(l));
printf("The square root of %f is %f\n", d, sroot(d));
return 0;
}
```
希望这可以回答您的问题!
阅读全文
相关推荐











