dimanche 29 août 2021

How to check if modulus of 2 number is equal to 0 or not

Few days ago I wrote a program to check if a number have a square root with no decimal point. And I wrote a simple program code below:

#include <iostream>
#include <math.h>

int checkforFloat(int x, int y)
{
    //will return 0 if no remainder remains, other value meaning has remainder
    return x%y;
}

int main()
{
    while(true)
    {
        std::cout << "Enter number to check if it has square root: ";
        double squareNumber{};
        std::cin >> squareNumber;

        double squareRoot{sqrt(squareNumber)};

        if(checkforFloat(squareNumber, squareRoot)==0)
        {
            std::cout<<"The number you entered has a square root number, and that is " << squareRoot << '\n';
        }
        else if(checkforFloat(squareNumber, squareRoot)!=0)
        {
            std::cout<<"Sorry, " << squareNumber << " has no square root.\n";
        }
    }

    return 0;
}

and the output for this program looks like this:

Enter number to check if it has square root: 25
The number you entered has a square root number, and that is 5
Enter number to check if it has square root: 24
The number you entered has a square root number, and that is 4.89898
Enter number to check if it has square root: 225
The number you entered has a square root number, and that is 15
Enter number to check if it has square root: 226
Sorry, 226 has no square root.

As you can see, this line is not working properly (or I am unable to understand where is the problem) else if(checkforFloat(squareNumber, squareRoot)!=0) I don't know what's going on but the thing what is going wrong with this program is it prints the square rooted number even if the square root is floating point number. In the other hand if I use int not double as data type for variable squareNumber and squareRoot it doesn't work for me. I'm not sure if the problem is in the else if statement or not. I'm new to C++ so it's kinda hard for me to know what is going wrong.

Aucun commentaire:

Enregistrer un commentaire