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

查看:17
本文介绍了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++ - 如何找到整数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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