Log 函数的实现,但对于表示为字符串 C 的数字

发布于 2025-01-16 08:09:09 字数 1432 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

給妳壹絲溫柔 2025-01-23 08:09:09

您需要将字符串转换为数字

 char * numStr = "2.7";
 double num = strtod(numStr, NULL);
 

You need to convert the string to a number

 char * numStr = "2.7";
 double num = strtod(numStr, NULL);
 
飘过的浮云 2025-01-23 08:09:09

感谢@EricPostpischil 的回答
执行长除法,将输入数字除以基数并丢弃余数。重复执行此操作并计算重复次数即可得出对数(直到商小于 1 为止的重复次数是不大于对数的最大整数;
我认为@pmg的答案也是一个好方法

thanks to @EricPostpischil for the answer
perform long division, dividing the input number by the base and discarding the remainder. Doing this repeatedly and counting the repetitions produces the logarithm (the number of repetitions until the quotient is less than one is the greatest integer not greater than the logarithm;
the answer of @pmg is also a good way to do it i thinks

安稳善良 2025-01-23 08:09:09

即使你的示例函数也有拼写错误。看来您的意思是返回 n 的对数底 x 的整数部分,并对结果应用下限函数。要实现这一点,它必须是:

int logn(int n, int x)           // n is the number, x is the base
{
    if (n <= x - 1) return 0;    // note: x, not r
    return (1 + logn(n / x, x);  // note: x, not 2 for the division
}

话虽这么说,我看不出有任何方法可以在不首先将其转换为数值的情况下对字符串化数字取任意基对数。如果您只想要一个以 10 为底的对数,这是可能的。

Even your example function has typos in it. It appears you meant for it to return the integer part of the logarithm base x of n, with a floor function applied to the result. To accomplish this it would have to be:

int logn(int n, int x)           // n is the number, x is the base
{
    if (n <= x - 1) return 0;    // note: x, not r
    return (1 + logn(n / x, x);  // note: x, not 2 for the division
}

All that being said, I don't see any way of taking an arbitrary-base logarithm of a stringified number without converting it to a numeric value first. If you wanted only a base-10 logarithm, it would be possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文