简体   繁体   English

无符号函数可使用任何数字返回数字

[英]Unsigned function to return digits using any numbers

I'm working on an exercise where I have to program an unsigned function in C++ --- The function has returned the number of digits in num and must work on any number. 我正在做一个练习,我必须在C ++中编写一个无符号函数---该函数返回了num位数,并且必须可以处理任何数字。

The issue  --- when I do unsigned num is greater than 10 digits, it still 
shows 10 as the answer.  what am I doing wrong?


unsigned numDigits(unsigned num)  
{
if (num == 0)
return 0; 
return 1 + numDigits(num / 10); 
return (num);
}

int main()
{
unsigned num = 12345678901;
cout << "Number of Digits: " << numDigits(num);
}

unsigned size is: 无符号大小为:

0 to 65,535 or 
0 to 4,294,967,295 (10 digits)

So change your funtion into: 因此,将功能更改为:

unsigned numDigits(long long unsigned num)

A cheat solution to your problem is also: 解决您的问题的方法还包括:

std::string dig = std::to_string(num);
std::cout << dig.size();
 unsigned getNumDigits(long long unsigned num)
 {
      if (num < 9 )
          return 1;
       return 1 + getNumDigits(num / 10 );
 }

@ram , thx for pointing out. @ram,指出。 Max guaranteed unsigned value is 65535 . 最大保证的无符号值是65535。 Accomodating values more than this will need a bigger (value accomodating) type. 容纳更多的值将需要更大的(容纳值的)类型。 Max unsigned value is possible with long long unsigned . 使用long long unsigned可以实现最大无符号值。 A value 0 also mean 1 digit hence comparison against 9 . 值0也表示1位数字,因此与9比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM