This is a simple weight conversion program. The purpose is to divide EnglishWeight1 5 pounds 12 ounces by number. I use the try-throw-catch method to handle division by 0.
Please help.
//Class Declaration
class EnglishWeight
{
private:
int pounds, ounces;
public:
EnglishWeight(void); //0-argument constructor
EnglishWeight(int lbs, int oz);
EnglishWeight ScalarDivision(const int &s, int *check) const;
};
//Member Function Definition
EnglishWeight::EnglishWeight(void)
{
pounds = ounces = 0;
}
EnglishWeight::EnglishWeight(int lbs, int oz)
{
pounds = lbs;
ounces = oz;
}
EnglishWeight EnglishWeight::ScalarDivision(const int &s, int *check) const //Scalar Division function
{
EnglishWeight sdivide; //Declare variable
try
{
if (s == 0) //DIV/0 check
throw 0;
else
{
sdivide.ounces = (pounds * 16) + ounces;
sdivide.pounds = sdivide.ounces / (16 * s);
sdivide.ounces = sdivide.ounces % 16;
return sdivide;
}
}
catch (int x)
{
*check = x;
}
}
void EnglishWeight::Show() const
{
std::cout << pounds << " pounds, " << ounces << " ounces";
}
//Main Driver
int main(void)
{
EnglishWeight EnglishWeight1(5, 12);
EnglishWeight sdiv1;
int number = 0;
int flag = 1;
sdiv1 = EnglishWeight1.ScalarDivision(number, &flag);
if (flag == 0)
std::cout << "EnglishWeight1 / number = DIV/0" << std::endl;
else
{
std::cout << "EnglishWeight1 / number = ";
sdiv1.Show();
std::cout << std::endl;
}
}
Error: 0xC0000005: Access violation reading location 0x0000000000000000 which probably means the compiler is reading garbage value somewhere. I just don't know how to fix it.
@WhozCraig suggestion works. Thanks!
"There is no return specified in the case where the div-0 exception happens. Therefore you're basically lying to the caller of EnglishWeight1.ScalarDivision in claiming you'll return a EnglishWeight on all code paths. Frankly, I cannot fathom how your compiler did not emit some sort of warning about "not all code paths provide return value" or some similar phrasing."
"Just return sdivide as-is. Your caller isn't going to use it regardless"
User contributions licensed under CC BY-SA 3.0