C语言计算位数
现在,我们将研究如何计算整数中的位数。这个整数不过是用户输入的数字。
首先,我们将使用for或while循环计算计数位数。
方法
首先,该数字将由用户输入。假设我们声明了变量" n"并将整数值存储在" n"变量中。
我们将创建一个while循环,该循环将迭代直到'n'的值不等于零。
假设" n"的值为123、
执行第一次迭代时," n"的值为123,count的值将递增为1、
执行第二次迭代时," n"的值为12,count的值将增加为2、
执行第三次迭代时," n"的值将为1,count的值将增加为3、
第三次迭代完成后," n"的值变为0,并且由于不满足条件(n!= 0)而终止循环。
让我们创建一个将实现上述方法的程序。
#include <stdio.h>
int main()
{
int n; // variable declaration
int count=0; // variable declaration
printf("Enter a number");
scanf("%d",&n);
while(n!=0)
{
n=n/10;
count++;
}
printf("\nThe number of digits in an integer is : %d",count);
return 0;
}
输出
对数字进行计数现在,我们将了解如何在不使用循环的情况下计算位数。
我们也可以使用对数函数的帮助。位数可以使用log10(num)+1来计算,其中log10()是 math.h 头文件中的预定义函数。
让我们看看一个简单的例子。
#include <stdio.h>
#include<math.h>
int main()
{
int num; // variable declaration
int count=0; // variable declaration
printf("Enter a number");
scanf("%d",&num);
count=(num==0)?1:log10(num)+1;
printf("Number of digits in an integer is : %d",count);
return 0;
}
输出
我们将创建一个C程序,以使用函数对位数进行计数。
#include <stdio.h>
int main()
{
int num; // variable declaration
int count=0; // variable declaration
printf("Enter a number");
scanf("%d",&num);
count=func(num);
printf("Number of digits is : %d", count);
return 0;
}
int func(int n)
{
int counter=0; // variable declaration
while(n!=0)
{
n=n/10;
counter++;
}
return counter;
}
输出
现在,我们将看到如何使用递归来计算位数。
#include <stdio.h>
int main()
{
int num; // variable declaration
int count=0; // variable declaration
printf("Enter a number");
scanf("%d",&num);
count=func(num);
printf("Number of digits is : %d", count);
return 0;
}
int func(int n)
{
static int counter=0; // variable declaration
if(n>0)
{
counter=counter+1;
return func(n/10);
}
else
return counter;
}
在上面的程序中,我们正在计算整数中的位数。 func()函数被调用。在func()中,我们声明一个静态变量,即counter,该变量仅初始化一次。函数(n/10)将被称为递归,直到条件(n> 0)为真。条件为假时,将返回计数器的值。
输出