Create your own code that returns the square root of C language

--Returns the square root of a number. --0 if the square root is an irrational number

code

int ft_sqrt(int nb)
{
    int raiz;

    raiz = 0;
    while (raiz * raiz < nb){
        raiz++;
        if (raiz * raiz == nb)
            return raiz;
        if (raiz * raiz > nb)
            return 0;
    }
    return 0;
}

Impressions

nb <= 0 Even if you don't pinch it Write to judge at the first condition of while.

Instead of diversifying if statements, write after thinking whether it can be judged by the while conditional expression.

I think it's also good to start from 1 with raiz ++ immediately after while.

Recommended Posts