Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to write c++ programing for this question and just can only use iostream

+3 votes
asked Feb 16, 2020 by Alan Poh

Declare a, b, m, X, with suitable data types.

Ask the user politely to input a positive real number X;

If X is one, then output one;

Else,

    If X is greater than 1, then let a = 1, b = X;

    If X is less than 1, then let a = X, b = 1;

    // from the observation from Fact 1,

    // the solution must lie between a and b.

    As long as b – a is more than 0.000001 times a, do

        Let m = the midpoint of a and b;

        If the square of m is equal to X,

            Escape from the loop;            (*)

        If the square of m is more than X,

            Let b = m;

        If the square of m is less than X,

            Let a = m;

    Output the midpoint of a and b, claim it as image;

1 Answer

0 votes
answered Mar 8 by Aryan semwal (190 points)
#include <iostream>
using namespace std;

int main() {
    double a, b, m, X;

    cout << "Please enter a positive real number X: ";
    cin >> X;

    if (X == 1) {
        cout << "one" << endl;
    } else {
        if (X > 1) {
            a = 1;
            b = X;
        } else {
            a = X;
            b = 1;
        }

        while (b - a > 0.000001 * a) {
            m = (a + b) / 2;

            if (m * m == X) {
                break;
            } else if (m * m > X) {
                b = m;
            } else {
                a = m;
            }
        }

        cout << "The square root of " << X << " is approximately " << m << endl;
    }

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...