C++ - how to find the length of an integer(C++ - 如何找到整数的长度)
问题描述
我正在尝试找到一种方法来查找整数的长度(位数),然后将其放入整数数组中.该作业还要求在不使用 STL 的类的情况下执行此操作,尽管程序规范确实说我们可以使用通用 C 库"(我会问我的教授是否可以使用 cmath,因为我假设 log10(num)+ 1 是最简单的方法,但我想知道是否还有其他方法).
I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).
啊,这不必处理负数.唯一的非负数.
Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.
我正在尝试创建一个变体MyInt"类,它可以使用动态数组处理更广泛的值.任何提示将不胜感激!谢谢!
I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!
推荐答案
任意基数的整数n
的位数是通过除法得到的,直到你完成:
The number of digits of an integer n
in any base is trivially obtained by dividing until you're done:
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base;
} while (n);
这篇关于C++ - 如何找到整数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ - 如何找到整数的长度


基础教程推荐
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09