私は学校での 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))
メインを変更して、try/catch 部分を無限ループにします。try ブロックでは、長さと幅を尋ねます。cin が失敗した場合は戻り、そうでない場合は領域を出力し、その領域の mysqrt を出力します。プログラムに hw3pr2.cpp という名前を付けます。(たとえば、"end" という単語など、正しくフォーマットされていない int を入力すると、cin は失敗することを思い出してください。)
コードの読み方は理解していますが、開始するのに苦労しており、これまでのところ「スコープ」と混同されていますが、これまでのところ正しくコンパイルされていますが、Range Error: 10 が引き続き表示されます。クラスエリアが間違っていますか?
誰かが私を正しい方向に向けてもらえますか? ありがとうございました!