fork download
  1. // You need this for cin and cout
  2. #include <iostream>
  3.  
  4. // You need this for sqrt
  5. #include <cmath>
  6.  
  7. // You need this for lots of stuff
  8. using namespace std;
  9.  
  10. // Returns true if number is a perfect square
  11. bool IsSquare (int num)
  12. {
  13. // Calculate the square root of num
  14. // Casting to an int truncates any decimal parts
  15. int sqrt_num = sqrt(num);
  16.  
  17. // If the previous line didn't truncate and digits
  18. // then the number must be a perfect square.
  19. // If the square root squared equals the original
  20. // number it is a perfect square!
  21. return sqrt_num*sqrt_num == num;
  22. }
  23.  
  24. int main()
  25. {
  26. // Perfect squares only work on integers
  27. int num;
  28.  
  29. // Loop while num
  30. while(true){
  31. // Ask for number
  32. cout << "Enter number to determine if it is a perfect square: \n";
  33. cin >> num;
  34.  
  35. // Stop if number is less than 1
  36. if(num < 1) break;
  37.  
  38. // Number was a square
  39. if (IsSquare(num)) cout << num << " is a square\n";
  40.  
  41. // Number wasn't a square
  42. else cout << num << " is not a prefect square\n";
  43. }
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 2728KB
stdin
3
9
12
36
0
stdout
Enter number to determine if it is a perfect square: 
3 is not a prefect square
Enter number to determine if it is a perfect square: 
9 is a square
Enter number to determine if it is a perfect square: 
12 is not a prefect square
Enter number to determine if it is a perfect square: 
36 is a square
Enter number to determine if it is a perfect square: