Can not fix the error..

Hi guys.
The following program checks if a number is a perfect square.

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
#include <iostream>
using namespace std;

int main()
{

bool perfect_square = true;
int x;

cout << "please enter a number to test for perfect squareness";
cin >> x;

for(int i = -1; (  (i*i) <= x  );  i--)
{
    if(x = i*i)
    {
        cout << x << " is a perfect sqaure equal to: " << i << " * " << i << endl;
        pefect_square = true;
        break;
    }
}

if(!perfect_square)
{
    cout << x << " is not a perfect square" << endl;
}

return 0;
}


The compiler gives me a WARNING for line 15:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]

I do not know what it wants from me at all.


And an ERROR for line 18:
error: 'pefect_square' was not declared in this scope

Trying to fix this error, I naively tried to take what is in line 7 (bool perfect_square = true)
and put it in the global scope, above int main(). But I still get the same error....


Thanks!
Last edited on
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
#include <iostream>
using namespace std;

int main()
{

bool perfect_square = true; // *** note: this will never become false
int x;

cout << "please enter a number to test for perfect squareness";
cin >> x;

for(int i = -1; (  (i*i) <= x  );  i--)
{
    if(x = i*i) // *** warning: using the result of an assignment as a condition without parentheses
                //        note: use '==' to turn this assignment into an equality comparison
    {
        cout << x << " is a perfect sqaure equal to: " << i << " * " << i << endl;
        pefect_square = true; // *** error: use of undeclared identifier 'pefect_square'; did you mean 'perfect_square'?

        break;
    }
}

if(!perfect_square)
{
    cout << x << " is not a perfect square" << endl;
}

return 0;
}


This should suffice:
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>
// #include <cmath>

int main()
{
    int x;
    std::cout << "please enter a number to test for perfect squareness ";

    if( std::cin >> x && x >= 0 )
    {
        // for( int i = std::sqrt(x) - 1 ; (i*i) <= x ; ++i ) // #include <cmath>
        for( int i = 0 ; (i*i) <= x ; ++i )
        {
            if( x == i*i )
            {
                std::cout << x << " == " << i << " * " << i << '\n' ;
                return 0 ;
            }
        }
    }

    std::cout << x << " is not a perfect square\n" ;
}
Thank you so much. Perfect.
I can not believe I missed the == in an if statement... because I was telling myself a few weeks ago that "who would miss that?"... Me I guess : (

Thank you again.
Topic archived. No new replies allowed.