在 C++ 中找到大于给定数字的下一个完全平方数


假设我们有一个数字 n。我们的任务是找出 n 的下一个完全平方数。因此,如果数字 n = 1000,那么下一个完全平方数是 1024 = 322。

要解决这个问题,我们需要获取给定数字 n 的平方根,然后取其整数部分,然后再显示(整数部分 + 1)的平方

例如

#include<iostream>
#include<cmath>
using namespace std;
int justGreaterPerfectSq(int n) {
   int sq_root = sqrt(n);
   return (sq_root + 1)*(sq_root + 1);
   }
int main() {
   int n = 1000;
   cout << "Nearest perfect square: " << justGreaterPerfectSq(n);
}

输出

Nearest perfect square: 1024

更新于: 2019-11-04

455 次查看

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.