发现C中的整数的长度 [英] Finding the length of an integer in C

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

问题描述

我想知道我怎么能找到C中的整数的长度。

I would like to know how I can find the length of an integer in C.

例如:


  • 1 => 1

  • 25 => 2

  • 12512 => 5

  • 0 => 1

等。

我怎样才能做到这在C?

How can I do this in C?

推荐答案

为什么不拿基10日志数的绝对值,圆了下去,并添加一个?这适用于那些不为0的正数和负数,并避免了必须使用任何字符串转换函数

C:

Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.

日志10 ABS 地板功能通过文件math.h 提供。例如:

The log10, abs, and floor functions are provided by math.h. For example:

int nDigits = floor(log10(abs(the_integer))) + 1;

您应该的条款确保 the_integer在包装这个!= 0 ,因为 LOG10(0​​)收益<根据男子3日志 code> -HUGE_VAL

You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.

此外,您可能要添加一个最终的结果,如果输入的是负面的,如果你有兴趣,包括它的负号数的长度。

Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;


<强> N.B。涉及在该方法中计算的浮点性质可能导致其比一个更直接的方法慢。见Kangkan的回答对效率的一些讨论的意见。


N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.

这篇关于发现C中的整数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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