介绍
在本实验中,我们将学习如何使用 C++ 确定给定整数中的数字位数。我们将使用一个简单的逻辑,即将数字除以 10,并计算直到商变为 0 所需的除法次数。
在本实验中,我们将学习如何使用 C++ 确定给定整数中的数字位数。我们将使用一个简单的逻辑,即将数字除以 10,并计算直到商变为 0 所需的除法次数。
首先,我们需要在项目目录中创建一个新的 C++ 文件。打开终端并使用 cd ~/project
导航到你的项目目录。然后,使用 touch
命令创建一个名为 main.cpp
的新 C++ 文件:
touch main.cpp
在这一步中,我们将编写一个 C++ 程序来计算给定数字中的位数。将以下代码复制并粘贴到你的 main.cpp
文件中:
// C++ program to count number of digits in a given number
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to count the number of digits in a given number ===== \n\n";
//variable declaration
int n, n1, num = 0;
//taking input from the command line (user)
cout << " Enter a positive integer : ";
cin >> n;
n1 = n; //storing the original number
//Logic to count the number of digits in a given number
while (n != 0)
{
n /= 10; //to get the number except the last digit.
num++; //when divided by 10, updated the count of the digits
}
cout << "\n\nThe number of digits in the entered number: " << n1 << " is " << num;
cout << "\n\n\n";
return 0;
}
在这个程序中,我们从用户那里获取一个正整数并将其存储在变量 n
和 n1
中。我们将 num
初始化为 0
,它将存储数字的位数计数。然后,我们使用一个 while
循环来计算位数。在每次迭代中,我们将数字除以 10,并将位数计数增加 1。我们继续这个循环,直到商变为零。
循环结束后,我们显示 num
的值,它保存了输入数字中的位数计数。
现在,我们需要编译并运行我们的程序。在终端中,输入以下命令来编译 main.cpp
文件:
g++ main.cpp -o main
成功编译后,使用以下命令运行程序:
./main
程序将显示一个提示,要求输入数字。输入一个正整数并按 Enter 键。程序将处理输入并打印输入数字中的位数。
在本实验中,我们学习了如何使用 C++ 确定给定整数中的数字位数。我们使用了一个简单的逻辑,即将数字除以 10,并计算直到商变为 0 所需的除法次数。
我们创建了一个 C++ 程序,该程序从用户那里获取一个正整数并计算该数字中的位数。我们使用终端编译并运行了该程序,并使用不同的输入整数进行了测试。