判断完全平方数

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何在 C++ 编程语言中判断一个给定的数字是否为完全平方数。为了实现这一目标,我们将使用 C++ 的 sqrt() 方法来计算输入数字的平方根。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/StandardLibraryGroup -.-> cpp/math("`Math`") subgraph Lab Skills cpp/conditions -.-> lab-96130{{"`判断完全平方数`"}} cpp/function_parameters -.-> lab-96130{{"`判断完全平方数`"}} cpp/output -.-> lab-96130{{"`判断完全平方数`"}} cpp/user_input -.-> lab-96130{{"`判断完全平方数`"}} cpp/math -.-> lab-96130{{"`判断完全平方数`"}} end

包含必要的库

在这一步中,你需要包含必要的库。iostream 库用于输入和输出,math.h 库用于计算平方根。

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

using namespace std;

定义一个函数来检查完全平方数

在这一步中,定义了 isPerfectSquare() 方法,该方法接受一个整数,如果给定的数字是完全平方数,则返回 true。在此方法中,我们首先使用 C++ 的 sqrt() 方法计算输入数字的平方根。如果输入数字的平方根是整数,则该数字是完全平方数。

bool isPerfectSquare(int n)
{
    int sr = sqrt(n);

    if (sr * sr == n)
        return true;
    else
        return false;
}

读取用户输入并调用方法检查完全平方数

在这一步中,我们使用 main() 方法读取用户输入并调用 isPerfectSquare() 方法来检查是否为完全平方数。首先,我们提示用户输入一个正整数。然后调用 isPerfectSquare() 方法检查输入的数字是否为完全平方数。如果输入的数字是完全平方数,我们将向用户显示该数字的平方根。如果输入的数字不是完全平方数,我们将显示相应的提示信息。

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to determine if the entered number is perfect square or not ===== \n\n";

    int n;
    bool perfect = false;

    cout << " Enter a positive integer:  ";
    cin >> n;

    perfect = isPerfectSquare(n);

    if (perfect)
    {
        cout << "\n\nThe entered number " << n << " is a perfect square of the number " << sqrt(n);
    }
    else
    {
        cout << "\n\nThe entered number " << n << " is not a perfect square";
    }

    cout << "\n\n\n";

    return 0;
}

编译并运行代码

要编译并运行代码,请在 Ubuntu 的终端中运行以下命令:

$ cd ~/project
$ g++ main.cpp -o main && ./main

输入一个正整数并按回车键。程序将输出输入的数字是否为完全平方数。

总结

在本实验中,你学习了如何在 C++ 编程语言中判断一个给定的数字是否为完全平方数。你还学习了如何使用 C++ 的 sqrt() 方法来计算输入数字的平方根。通过遵循上述步骤,你现在可以创建自己的程序来判断一个数字是否为完全平方数。

您可能感兴趣的其他 C++ 教程