forked from ShiqiYu/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error4.cpp
52 lines (46 loc) · 1.36 KB
/
error4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cstdlib>
#include <cfloat>
#include <cmath>
float ratio(float a, float b)
{
if (a < 0)
throw 1;
if (b < 0)
throw 2;
if (fabs(a + b) < FLT_EPSILON)
throw "The sum of the two arguments is close to zero.";
return (a - b) / (a + b);
}
int main()
{
float x = 0.f;
float y = 0.f;
float z = 0.f;
std::cout << "Please input two numbers <q to quit>:";
while (std::cin >> x >> y)
{
try{
z = ratio(x,y);
std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl;
}
catch(const char * msg)
{
std::cerr << "Call ratio() failed: " << msg << std::endl;
std::cerr << "I give you another chance." << std::endl;
}
catch(int eid)
{
if (eid == 1)
std::cerr << "Call ratio() failed: the 1st argument should be positive." << std::endl;
else if (eid == 2)
std::cerr << "Call ratio() failed: the 2nd argument should be positive." << std::endl;
else
std::cerr << "Call ratio() failed: unrecognized error code." << std::endl;
std::cerr << "I give you another chance." << std::endl;
}
std::cout << "Please input two numbers <q to quit>:";
}
std::cout << "Bye!" << std::endl;
return 0;
}