初中语文小知识:c++中如何知道int类型变量的长度?

来源:百度文库 编辑:神马品牌网 时间:2024/04/28 15:25:06
例子:
int int_tmp,count_int;
int_tmp=54321;
怎么让count_int==(int_tmp的长度5)?

没有现成的,只能够自己写一个了:
1. rv2001提供的算法就可以,但是不明确,改造一下:
int GetLength(const int tmp)
{
int count=0;
while( tmp/10 )
count++;
return count;
}

2. 利用字符数组来变通的获取:
int GetLength(const int tmp)
{
char str[16];
memset(str, 0, sizeof(str));
sprintf(str, "%d", tmp);

return strlen(str);
}

int length(int t)
{
int count =0;

while(t)
{
t=t/10;

++count;
}
return count;

}
//另外那个数如果是0或者是个负数,需要特判。如果是0调用这个函数之后,结果+1,负数调用这个函数之后,结果也要+1.

这个得写一个算法
int count=0;
while(temp=(int)(tmp/10))count++;
cout<<temp;

没有这样的函数的,要自己编写

取串长度函数length/strlen()