反转输入的数字

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将学习如何在 C++ 编程语言中找到给定数字的反转数。反转输入数字的概念可以用于检查回文数(Palindrome)。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/while_loop -.-> lab-96138{{"`反转输入的数字`"}} cpp/output -.-> lab-96138{{"`反转输入的数字`"}} cpp/user_input -.-> lab-96138{{"`反转输入的数字`"}} cpp/files -.-> lab-96138{{"`反转输入的数字`"}} cpp/code_formatting -.-> lab-96138{{"`反转输入的数字`"}} end

创建 C++ 源文件

首先,我们需要在 ~/project 目录下创建一个 C++ 源文件。打开终端并输入以下命令来创建一个名为 main.cpp 的文件:

touch ~/project/main.cpp

然后使用文本编辑器编辑 main.cpp 文件。

编写 C++ 代码

将以下代码添加到 main.cpp 文件中,这段代码将用于查找给定数字的反转数。

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

using namespace std;

//返回输入数字的反转数
int findReverse(int n)
{
    int reverse = 0; //用于存储给定数字的反转数
    int remainder = 0;

    //计算数字反转的逻辑
    while (n != 0)
    {
        remainder = n % 10; //存储个位数字
        reverse = reverse * 10 + remainder;
        n /= 10;
    }

    return reverse;
}

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " ===== 计算输入数字反转数的程序 ===== \n\n";

    //变量声明
    int n;
    int reverse = 0;

    //从命令行(用户)获取输入
    cout << " 请输入一个正整数以查找其反转数:";
    cin >> n;

    //调用返回输入数字反转数的方法
    reverse = findReverse(n);

    cout << "\n\n输入的数字是 " << n << ",其反转数为:" << reverse;

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

    return 0;
}

这段代码定义了两个函数:findReversemainfindReverse 接受任意整数作为参数并返回反转后的数字。main 是程序的主函数,它从用户那里获取输入并调用 findReverse 来返回反转后的数字。

编译并运行 C++ 代码

要编译并运行程序,请在终端中输入以下命令:

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

总结

在本实验中,我们学习了如何在 C++ 编程语言中找到给定数字的反转数。这一概念可以用于检查回文数(Palindrome)。通过使用循环,我们可以分解给定整数的每一位数字并反转它,从而找到最终的反转值。我们还学习了如何编译、运行和测试这个 C++ 程序。

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