c++ - 使用任何数字返回数字的无符号函数

标签 c++ c++11 visual-c++ c++-cli

我正在做一个练习,我必须编写一个未签名的 C++ 中的函数 --- 该函数返回了位数 in 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);
}

最佳答案

无符号大小为:

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

所以把你的函数改成:

unsigned numDigits(long long unsigned num)

您的问题的作弊解决方案也是:

std::string dig = std::to_string(num);
std::cout << dig.size();

关于c++ - 使用任何数字返回数字的无符号函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509470/

相关文章:

c++ - 现在我可以替换所有 Date 类吗?

c++ - C环境初始化裸机ARM GCC

C++类继承,对基类成员函数的 undefined reference

c++ - 它在 C++ 标准中的哪个位置记录了用户定义类型的 I/O?

c++ - 为什么 std::exception 在 VC++ 中有额外的构造函数?

c++ - 等待另一个应用程序窗口

c++ - 如何定义等于 16 字节的类型

c++ - 在编译时确定指针类型

c++ - 收到错误 C4013 - __readcr() 未定义;假设 extern 返回 int

c++ - 为什么 std::swap 不能在 std::aligned_union 上工作