square roots

hello i need a script that when the squareroot of a number is an int that he ouputs that int or 1;
for example sqrt(25)=5;sqrt(36)=6; sqrt(17)!= int;
heres a start to it
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
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	float n,sqi,i;
	cin >> n;  
	for (i=1;i<n;i++)
	{
		sqi=sqrt(i);
	   if () // i have to know this condition
	   {
		   if(i%2==0)
		   {
			   cout <<sqi<<endl;
		   }
		   else
		   {
			   cout <<"1"<< endl;
		   }
	   }
	}
	system("pause");
    return 0;
	}
Last edited on
You need to know whether a number is a perfect square?

Here's an example that will hopefully show you what to do.

1
2
3
4
5
int x = 26;

int sqrt_x = sqrt(x);

cout << x << " " << sqrt_x*sqrt_x;
Last edited on
ive looked sqrt function up and you can only take squareroot from:
-float
-double
-long double

and not from int.
Last edited on
Something like this:

1
2
3
4
5
6
int number ;
std::cin >> number ;
int i = std::sqrt(number) ; // C++98: std::sqrt( double(number) ) ;
if( number == i*i ) std::cout << i << '\n' ;
else if( number == (i+1)*(i+1) ) std::cout << i+1 << '\n' ;
else std::cout << 1 << '\n' ;

i have improved my code but it still doesnt works. i used the type casting from the post above(in the comment).
i can compile this code but it outputs nothing. can someone tell me why and how i can fix it.
here is the code:
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
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	float n,i,sqi;
	int ii,sqii;
	cin >> n;  
	for (i=1;i<n;i++)
	{
		sqi=sqrt(i);
		sqii=sqrt(double(ii));
	   if (sqi==sqii)
	   {
		   if(int(i)%2==0) //we need an int to use the % operator.
		   {
			   cout <<sqi<<endl;
		   }
		   else
		   {
			   cout <<"1"<< endl;
		   }
	   }
	}
	system("pause");
    return 0;
	}
Last edited on
What's ii?
Try running this and see what happens

1
2
3
4
5
6
7
8
for (int i = 1; i <= 100; i++)
{
    int sqrt_i = sqrt(i);
    if (i == sqrt_i*sqrt_i)
     {
        cout << i << " is a perfect square" << endl;
    }
}


if you're really worried about sqrt taking floats (although I suspect most compilers would be happy taking an int input), do this

1
2
3
4
5
6
7
8
for (int i = 1; i <= 100; i++)
{
    int sqrt_i = sqrt((float)i);
    if (i == sqrt_i*sqrt_i)
     {
        cout << i << " is a perfect square" << endl;
    }
}
Last edited on
oh my god. thank you.
for the people intrested add
ii=i; to the code above sqi=sqrt(i);
Topic archived. No new replies allowed.