问题描述:
【项目1-平方根中的异常】
编写一个程序,求输入数的平方根。设置异常处理,当输入负数时采用异常处理机制给出提示。
代码实现:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(){
double a;
try{
printf("请输入一个数:");
scanf("%lf",&a);
double b;
if(a>0)
b=sqrt(a);
else throw a;
cout<<a<<"的平方根是"<<b;
}
catch (double){
printf("输入错误!");
}
return 0;
}
运行结果: