求一个数是几位数的几种方法

第一种:数字分割法

代码如下:

#include <stdio.h>

void main()

{
    int x,b=0;
    scanf("%d",&x);
    while(x>0)
    {
        x=x/10;
        b++;
    }
    printf("%d ",b);
}

第二种:log10法

C语言中只有log和log10两种函数。 

如果想表达log a,b 那么可以使用log(b)/log(a)来解决。

代码如下:

#include<iostream>
#include<cmath>
using namespace std;
int main() 
{
    int n;
    cin>>n;
    cout<<(int)(log10(n))+1;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zjy_code/article/details/80667840
今日推荐