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);
相关文章