Help needed

This is what i have written so far :


#include<iostream>
#include<cmath>
using namespace std;

int main() {
int n;

cout<<"Please enter an integer :"<<endl;
cin>>n;


****************************
This is my objective :
Write a program which reads an integer n entered by the user and prints true if n is a perfect square and false if it is not. Im not sure as to how to go about doing this with an If statement / boolean operations and I'd appreciate all the help I can get :)

*I know how to do an IF statement and how to use booleans. I'm just not clear on how to get it to check to see if it is a perfect number or not*
Thanks
Last edited on
After 10 minutes thinking and working(on paper) with my mathematical brain and God helping me, this is the formula/code I got:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    int x;
    int check=0;

    cout<<"Enter a number: ";
    cin>>x;
    for(int i=0;i<99999999;i++)
        if(x==i*i)
        {
            cout<<"\nYes!, "<<x<<" is a perfect square!";
            check=1;
            break;
        }
    if(check!=1)
        cout<<"\nNo "<<x<< " is not a perfect square!";
    cin.ignore();
    cin.get();
}


Hope it HELPS!!!
Also, another version to tell what it's square root is:

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int x;
    int check=0;

    cout<<"Enter a number: ";
    cin>>x;
    for(int i=0;i<99999999;i++)
        if(x==i*i)
        {
            cout<<"\nYes!, "<<x<<" is a perfect square!";
            cout<<"\n"<<sqrt(x)<<" is it's square root!";
            check=1;
            break;
        }
    if(check!=1)
        cout<<"\nNo "<<x<< " is not a perfect square!";
    cin.ignore();
    cin.get();
}
The code that @Aceix provided is a bit of overkill.

However, he (or she?) mentioned the sqrt() function found in <cmath>.

The following code segment:

1
2
3
4
5
6
7
8
9
#include <cmath>

...

   int x = ...
   int root = sqrt(x);

...


will give you the largest integer which is <= the square root of x. Form there you can check whether x is a perfect square.
Topic archived. No new replies allowed.