在C中查找整数的长度 [英] Finding the length of an integer in C

查看:17
本文介绍了在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?

推荐答案

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.

log10absfloor 函数由 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) 根据 返回 -HUGE_VAL>man 3 日志.

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. 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天全站免登陆