编写一个程序,求输入数的平方根。设置异常处理,对输入负数的情况给出提示。 提示:#include<math> #include <iostream> using namespace std; double Sq(double x) { if (x < 0) throw x; return sqrt(x); } ……
时间: 2024-01-21 21:18:32 浏览: 36
下面是一个示例程序,实现了输入数的平方根并进行了异常处理:
```C++
#include <iostream>
#include <math.h>
using namespace std;
double Sq(double x) {
if (x < 0)
throw "负数没有平方根!";
return sqrt(x);
}
int main() {
double num;
cout << "请输入一个数:";
cin >> num;
try {
double res = Sq(num);
cout << "该数的平方根为:" << res << endl;
}
catch (const char* msg) {
cerr << "错误: " << msg << endl;
}
return 0;
}
```
在上述代码中,我们定义了一个 `Sq` 函数用于计算输入数的平方根。如果输入的数为负数,则会抛出一个异常,并且提示 `"负数没有平方根!"`。
在主函数中,我们首先读入一个数并调用 `Sq` 函数计算其平方根。如果计算成功,则输出结果;否则,捕获异常并输出错误消息。
相关问题
编写一个程序,求输入数的平方根。设置异常处理,对输入负数的情况给出提示。提示:#include<math>#include <iostream>using namespace std;double Sq(double x){if (x < 0)throw x;return sqrt(x);}
好的,以下是一个求输入数平方根的程序,其中包括异常处理:
```cpp
#include <iostream>
#include <math.h>
using namespace std;
double Sq(double x){
if (x < 0) {
throw "输入数为负数!";
}
return sqrt(x);
}
int main() {
double x;
cout << "请输入一个数:";
cin >> x;
try {
double result = Sq(x);
cout << "平方根为:" << result << endl;
}
catch(const char* msg) {
cerr << "错误: " << msg << endl;
}
return 0;
}
```
在这个程序中,我们定义了一个函数`Sq`,用于计算输入数的平方根。如果输入数为负数,我们使用`throw`语句抛出一个字符串异常。在`main`函数中,我们使用`try`语句块来调用`Sq`函数。如果函数执行成功,我们输出结果;否则,我们使用`catch`语句块来捕获并输出异常信息。
注意,在`catch`语句块中,我们使用了`const char*`类型的异常类型,这是因为我们在`throw`语句中抛出的是一个字符串常量。如果我们抛出的是一个数值类型异常,如在`Sq`函数中抛出的`x`,我们可以使用相应的数值类型作为异常类型,如`double`。
⦁ 编写一个程序,要求用户输入一个整数。如果该数为正数,则输出该数的平方根;如果该数为负数,则输出该数的绝对值。
您好,根据您的要求,我可以回答您的问题。以下是程序的代码:
#include <stdio.h>
#include <math.h>
int main()
{
int num;
double result;
printf("请输入一个整数:");
scanf("%d", &num);
if(num >= )
{
result = sqrt(num);
printf("%d的平方根为%.2f\n", num, result);
}
else
{
result = fabs(num);
printf("%d的绝对值为%.2f\n", num, result);
}
return ;
}
感谢您的提问!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)