Sqrt and modulus

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  /*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>
using namespace 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);
}
You could make a bool function that checks if a number is perfect or not, just like this:
1
2
3
4
5
6
7
8
9
10
11
bool isSquare(int num){
double check1 = sqrt(num);
int check1 = sqrt(num);
double check_final = check1;
if (check_final == check1){
return true;
}
else{
return false;
}
}


Use it as you need in int squareRoot(int num)
Do you understand how modulus works? X mod 1 is always going to be 0.

Since you are trying to find out if num is a perfect square, try writing down how you would do that first then try translating it into code.
@jgg2002 Professor doesn't want a bool function for it but tyvm ^^
@firedraco Not really sure how modulus works unfortunately.
@pheliont
Not really sure how modulus works


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;
}
Topic archived. No new replies allowed.