Checking if a number is perfect square?

后端 未结 8 2029
野趣味
野趣味 2021-02-10 01:10

I think there is a precision problem with the following code:

bool isPerfectSquare(long long n){
    long long squareRootN=(long long)(sqrt(n)+0.5);

    return          


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-10 01:35

    You use round.

    bool isPerfectSquare(long long n){
        long long squareRootN=(long long)round((sqrt(n)));
    
        if(squareRootN*squareRootN == n) {
            return true; 
        }
         else {
            return false; 
         }
    

    round rounds the number to the nearest rounding. The function will be true only if n is a perfect square.

提交回复
热议问题