Feb 24, 2012 at 1:37pm UTC
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 Feb 24, 2012 at 1:55pm UTC
Feb 24, 2012 at 1:49pm UTC
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 Feb 24, 2012 at 1:49pm UTC
Feb 24, 2012 at 1:53pm UTC
ive looked sqrt function up and you can only take squareroot from:
-float
-double
-long double
and not from int.
Last edited on Feb 24, 2012 at 1:54pm UTC
Feb 24, 2012 at 2:04pm UTC
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 Feb 24, 2012 at 2:08pm UTC
Feb 24, 2012 at 2:11pm UTC
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 Feb 24, 2012 at 2:12pm UTC
Feb 24, 2012 at 2:12pm UTC
oh my god. thank you.
for the people intrested add
ii=i;
to the code above sqi=sqrt(i);