209 words
1 minutes
Test article
2024-11-17

Test

Second level directory#

Third level directory#

#include <iostream>
#include <stdlib.h>
#include <cmath>

// Define a function to calculate the square root
double calculateSquareRoot(double a, double epsilon = 1e-5) {
    // Initial guess value
    double x_n = a / 2.0;
    // Iterative solution
    while (true) {
        double x_n_plus_1 = 0.5 * (x_n + a / x_n);
        // Check if the accuracy requirement is met
        if (std::abs(x_n - x_n_plus_1) < epsilon) {
            return x_n_plus_1;
        }
        x_n = x_n_plus_1;
    }
}

int main() {
    double a;
    bool validInput = false; // Mark input as valid

    // Loop until the user enters a valid positive number
    while (!validInput) {
        std::cout << "Please enter a positive number to calculate its square root: ";
        std::cin >> a;

        // Check the input stream state to make sure the input is a number
        if (std::cin.fail()) {
            // If the input fails, reset the input stream and ignore the incorrect input
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Error: Input must be a positive number, please re-enter.\n";
        } else if (a > 0) {
            validInput = true;
        } else {
            std::cout << "Error: Input must be a positive number, please re-enter. \n";
        }
    }

    double result = calculateSquareRoot(a);
    std::cout << "Square root is: " << result << std::endl;

    system("pause");

    return 0;
}

Astro

Test article
https://en.moiland.com/posts/1/
Author
Motrans
Published at
2024-11-17