So I am having a problem. I'm doing an assignment for class, and I'm learning how to try, throw, and catch. In the function named squareRoot, I'm trying to get the catch to work using modulus and sqrt. The if statement is where the problem is. I've tried multiple combinations and can't seem to figure it out. Any help is appreciated.
/*Write a function that accepts an integer parameter and returns its
integer square root. The function should throw an exception if it is
passed an integer that is not a perfect square.
Demonstrate the function with a suitable driver program.*/
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
//Prototype
int squareRoot(int);
int main()
{
int num;
double square;
cout << "Enter the number you want the square root of." << endl;
cin >> num;
try
{
square = sqrt(num);
squareRoot(square);
cout << "The square root is " << sqrt(num) << endl;
}
catch (string exception)
{
cout << exception;
}
system("pause");
return 0;
}
int squareRoot(int num)
{
//Stuck. No matter what I put, I have a problem getting the throw to pop up if I don't get a perfect square using %.
//I have gotten the throw to pop up by forcing it.
if (num %1 != 0)
throw string("Does not have a perfect square.\n");
return sqrt(num);
}
Modulus just returns the remainder of a division. For example 3%2=1 because 3 divided by one is 1*2 + 1. Another example is 200%50 = 0. Because 200 = 50*4 + 0.
I would expect the function to look more like the following:
1 2 3 4 5 6 7 8 9
int squareRoot(int num)
{
auto value = int { sqrt(num) };
if (value*value != num) // better than checking if num is evenly divisible by value.
throw string("Does not have a perfect square.\n");
return value;
}