DEV Community

Analyze_
Analyze_

Posted on

Cpp Square Root Calculator

I like making calculators so I made one for square root. This uses the cmath package

Link

#include <cmath>
#include <iostream>
using namespace std;

int main() {
  string session = "y";

  while (session == "y") {
    int num = 0;
    cout << "What would you like to find the quare root of?\n";
    cin >> num;
    cout << sqrt(num) << "\nWould you like to continue session [y/n]?\n";
    cin >> session;
    cout << "\x1B[2J\x1B[H";
  } // end of session
  cout << "\x1B[2J\x1B[H";
  cout << "Ended session\n";
  return 1;
} // end of code
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tdvines profile image
thomas • Edited

Interesting project.

I made a few "improvements".
Let me know if there is something off.

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cctype>

class Solution {
public:

    void squareroot() 
    {
        std::string input = "y"; // initialize input
        char target = 'y'; // target character to check for

        while (true) {

            double num = 0.0;
            std::cout << "What would you like to find the square root of?\n";
            std::cin >> num;

            // check if input failed (not a number)
            if (std::cin.fail()) 
            {
                std::cin.clear(); // clear the fail flag
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard bad input
                std::cout << "\x1B[2J\x1B[H\n";
                std::cout << "Invalid input! Please enter a number.\n";
                continue; // ask again
            }

            std::cout << sqrt(num) << "\nWould you like to continue session [y/n]?\n";
            std::cin >> input;
            if (!check_input(input, target))
                break;
            std::cout << "\x1B[2J\x1B[H\n";
        } // end of session
        std::cout << "\x1B[2J\x1B[H";
        std::cout << "Ended session\n";
        // return 1;
    } // end of code
private:
    bool check_input(const std::string& input, char target)
    {
        std::string lower = input;
        // Transform the string to lowercase
        std::transform(lower.begin(), lower.end(), lower.begin(),
                    [](unsigned char c){ return std::tolower(c); });
        target = std::tolower(static_cast<unsigned char>(target));
        // Check if target character is in the transformed string
        return (lower.find(target) != std::string::npos);
    }
};

int main() 
{
    Solution solution;
    solution.squareroot();
}

Enter fullscreen mode Exit fullscreen mode