enigmuz
enigmuz

Reputation: 11

Assitance with C++ using pseudocode code (overflow/underflow)

I'm barely into my 4th week of C++ in school and was looking to be guided in the right direction.

 #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";
    }
}

And this is what the assignment is asking us;

   //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))

Change the main to have an infinite loop around the try/catch part; in the try block ask for length and width; if cin fails then return, otherwise print the area, and print mysqrt of the area. Name your program hw3pr2.cpp. (Recall that cin will fail if you type something that is not a properly-formatted int, e.g., the word "end".)

I understand how to read the code, but I'm having a hard time starting it, and sort of get confused with "scope" so far it compiles correctly but keeps on giving me Range Error: 10. does that mean I'm using the class area wrong?

could someone please point me in the right direction? Thank you!

Upvotes: 1

Views: 532

Answers (1)

Justin
Justin

Reputation: 406

You're declaring a vector of 10 elements and trying to access the 11th item with v[10].

[EDIT] As others have pointed out, std::vector doesn't do bounds checking by default, but if "std_lib_facilities_3.h" is similar to this, then it defines its own range-checked vector class.

[EDIT2] So you've updated your code so that length and width must be both greater than 0 or an BadArea exception will be thrown, but you're always calling area(7, -10), so you'll always get the exception. I think you want to pass the length and width to the area function: cout << area(length, width) << '\n';

Upvotes: 1

Related Questions