加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如果输入的数字不是一个完美的正方形,找到最近的完美正方形

发布时间:2020-12-16 10:52:46 所属栏目:百科 来源:网络整理
导读:#include iostream#include limits#include cmathusing namespace std;int main(){ int number; cout "Enter the number whose sqare root needs to be calculated"; cin number; cout "Square root of " number " is " (int)sqrt((float)number) " OR " sqr
#include <iostream>
#include <limits>
#include <cmath>

using namespace std;

int main()
{
    int number;
    cout << "Enter the number whose sqare root needs to be calculated";
    cin >> number;
    cout << "Square root of " << number << " is " << (int)sqrt((float)number)  << " OR " << sqrt((float)number) << endl;
    if( (int)sqrt((float)number) == sqrt((float)number) )
    cout << "The number is a perfect sqaure";
    else
    cout << "The number is not a perfect square";
    //To find the nearest perfect square if the number entered
   // is not a perfect square?

    return 0;
}

我希望我所做的检查完美的方块是可以的,但此外我想
如果输入的数字不是一个完美的正方形,找出最接近完美正方形的数字
有任何想法吗

解决方法

实际上,这是更好的答案:

int number = 13;
int iRoot = static_cast<int>(sqrt(static_cast<float>(number)) + .5f);

你不需要检查ceil或其底板是否更大,做一个简单的回合就可以了.

sqrt(13)是3.6,当你添加.5强制转换为4. sqrt(12)是3.46,当你添加.5强制转换为3.(我们试图舍入,这就是我们添加.5的原因).正如你所看到的,当数字更接近更高的根时,它会给你一个大于.5的小数;当数字更接近较低值的根时,小数小于.5,就这么简单!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读