我刚刚进入学校 C++ 的第 4 周,并希望得到正确的指导。
#include "std_lib_facilities_3.h"
class BadArea{};
int area(int length, int width){
if(length <= 0 || width <=0) throw BadArea();
return length * width;
}
double mysqrt(double x){
if(x < 0.0) error("mysqrt");
return 1.0; //dummy value for now, need to write code later
}
int main(){
try{
char length = 0;
char width = 0;
cout << "Enter length and width seperated by a space\n";
cin >> length;
cin >> width;
vector<double> v(10);
v[9] = 7.5;
cout << area(7, -10) << '\n';
cout << mysqrt(-2.0) << '\n';
return 0;
}
catch(BadArea){
cerr << "Exception: Bad area\n";
}
catch(exception& e){
cerr << "ExceptionZ: " << e.what() << '\n';
}
catch(...){
cerr << "Exception occurred\n";
}
}
这就是任务要求我们的;
//Check for overflow in the area function
result = length * width
if result is negative or result/length <> width, throw an exception
//Use 3 iterations of the Newton-Raphson method for mysqrt
if x is 0, result is 0 so return it
if x is 1, result is 1 so return it
otherwise,
result = (x^4 + 28x^3 + 70x^2 + 28x + 1)/(8*(1 + x)*(1 + 6x + x^2))
将 main 更改为在 try/catch 部分周围进行无限循环;在 try 块中询问长度和宽度;如果 cin 失败则返回,否则打印该区域,并打印该区域的 mysqrt。将您的程序命名为 hw3pr2.cpp。(回想一下,如果您键入的内容不是格式正确的 int,例如单词“end”,cin 将失败。)
我了解如何阅读代码,但我很难启动它,并且有点与“范围”混淆,到目前为止它编译正确但不断给我 Range Error: 10. 这是否意味着我正在使用课区错了?
有人可以指出我正确的方向吗?谢谢!