C++ Program to Find Square Root using Math Library

«
»
This C++ program computes the square root of a number using math library. The program takes input from the standard input, computes the value and prints it.

Here is the source code of the C++ program computes the square root of a number using math library. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Compute Square Root of a number using Standard Library
  3.  */
  4. #include <iostream>
  5. #include <cmath>
  6. #include <limits>
  7.  
  8. int main()
  9. {
  10.     double output, input, min, max;
  11.  
  12.     std::cout << "Enter the value : ";
  13.     std::cin  >> input;
  14.     std::cout << std::endl;
  15.     min = std::numeric_limits<double>::min();
  16.     max = std::numeric_limits<double>::max();
  17.     if (input >= min && input <= max)
  18.     {
  19.         output = sqrt(input);
  20.         std::cout << "Square root of " << input
  21.                   << " = " << output << std::endl;
  22.     }
  23.     else
  24.     {
  25.         std::cerr << "Error: " << input << " not within limits"
  26.                   << std::endl;
  27.     }
  28.     return 0;
  29. }

$ a.out
Enter the value : 1024.0
Square root of 1024 = 32

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.