c语言 输入一个整数 统计该整数的位数

如题所述

#include<stdio.h>
void main(void)
{
int num,digits=1;
printf("Input a number: ");
scanf("%d",&num);
printf("Number %d has ",num);
while(num/=10)++digits;
printf("%d digits.\n",digits);
return;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-22
 #include <stdio.h>
 main()
 {
  unsigned long num=0;
  int i=1,j=0;
  printf("请输入一个数:");
  scanf("%d",&num);
  while((num/i)>=1)
  {
   i=i*10;
   j++;
  }
  printf("该数为%d位数\n",j);
 }

有什么看不懂的问我,望采纳

追问

刚弄好

谢谢你啊

追答

我辛苦写了一遍,你就给个采纳嘛

追问

我不知道怎么点采纳啊

追答

下面有一个 采纳为满意答案 ,点一下就行啦~~~

追问

我这没有

追答

额,那好吧

本回答被网友采纳
第2个回答  2013-10-22

还有一种可以把数字转化成字符串,然后统计字符串的长度

#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int  main()
{

char str[10];
int num=0;
scanf("%d",&num);
itoa(num,str,10);//把整数转化成字符串

printf("\n这个整数的位数为:%d",strlen(str));//直接求字符串的长度

return 0;
}

第3个回答  推荐于2017-10-11
下面给出例子:
#include <stdio.h>
using namespace std;
int main()
{
char buff[100];
int a=100;
int b;
b=sprintf(buff,"%d",a);
printf("%d\n",b);
return 0;
}
在此程序中使用了为sprintf的函数;
格式为sprintf(字符型数组/字符型指针,要转换的数的格式,定义的数);
该函数返回的为输入的数的长度;
此例可以计算长度。
第4个回答  2013-10-23
#include <stdio.h>int main(){ int num = 0; int s = 0; int i = 0; scanf("%d", &num); while(num) { s += num%10; num = num/10; i++; } printf("数字个数为%d,各个数相加为%d\n",i, s ); return 0;