二つの実数x,yを入力する。x,yの符号が共に正ならば、その和の平方根を求める。符号が異なれば、“片方が負”、ともに負であれば“両方とも負”というメッセージを出力する例外処理を完成させよ。
入力例:
1 2
sqrt = 1.73205
-1 2
片方が負
-1 -2
両方が負
0 2
sqrt = 1.73205
#include<iostream> #include<cmath> using namespace std; void sq(double x, double y){ double z; if(x < 0.0 && y < 0.0) throw 0; else{ if(x < 0.0 || y < 0.0) throw 1; } z = sqrt(x+y); cout << "sqrt = " << z << endl; } int main(){ double x,y; while (x != 0){ cin >> x >> y; try{ sq(x,y); } catch (int sw){ switch (sw){ case 0: cout << "両方とも負\n"; break; case 1: cout << "片方が負\n"; break; } } } return 0; }
入力例:
1 2
sqrt = 1.73205
-1 2
片方が負
-1 -2
両方が負
0 2
sqrt = 1.73205
コメントをかく