你如何在 C# 中做*整数* 取幂?

编程入门 行业动态 更新时间:2024-10-28 00:19:33
本文介绍了你如何在 C# 中做*整数* 取幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

.NET 中的内置 Math.Pow() 函数将 double 基数提升为 double 指数并返回一个 double 结果.

The built-in Math.Pow() function in .NET raises a double base to a double exponent and returns a double result.

对整数执行相同操作的最佳方法是什么?

What's the best way to do the same with integers?

补充:似乎可以将 Math.Pow() 结果转换为 (int),但这会始终产生正确的数字并且没有舍入错误吗?

Added: It seems that one can just cast Math.Pow() result to (int), but will this always produce the correct number and no rounding errors?

推荐答案

一个相当快的方案可能是这样的:

A pretty fast one might be something like this:

int IntPow(int x, uint pow) { int ret = 1; while ( pow != 0 ) { if ( (pow & 1) == 1 ) ret *= x; x *= x; pow >>= 1; } return ret; }

请注意,这不允许负权力.我将把它留给你作为练习.:)

Note that this does not allow negative powers. I'll leave that as an exercise to you. :)

添加:哦,是的,差点忘了 - 还要添加上溢/下溢检查,否则您可能会遇到一些令人讨厌的惊喜.

Added: Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.

更多推荐

你如何在 C# 中做*整数* 取幂?

本文发布于:2023-11-03 06:58:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554507.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   中做   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!