自学内容网 自学内容网

[算法题]平方数

题目链接: 平方数

假如给出的数是 10, 那么 10 开平方约等于 3.16, 那么小于 3.16 且离其最近的整数为 3, 大于 3.16 且离其最近的整数为 4, 题意要求离 x 最近的完全平方数 y, 那么 3^2 和 4^2 与 10 的差值最小者即为解, 题解代码如下:
 

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    long n;
    cin >> n;
    long square_root = sqrt(n);
    long prev = pow(square_root, 2);
    long next = pow(square_root + 1, 2);   
    cout << ((n - prev < next - n) ? prev : next) << endl;
    return 0;
}

ps: sqrt() 为开平方函数, pow() 为求一个数的幂次方函数, 均为库函数.


原文地址:https://blog.csdn.net/m0_62714628/article/details/140621472

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!