C ++ - 如何查找整数的长度 [英] C++ - how to find the length of an integer

查看:276
本文介绍了C ++ - 如何查找整数的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来找到整数(位数)的长度,然后将其放在整数数组中。这个赋值还要求不使用STL中的类,尽管程序规范说我们可以使用common C libraries(请问我的教授是否可以使用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 ++ - 如何查找整数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆