用于电源但不使用 pow 函数的 C++ 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22133101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ program for power but without using pow function
提问by user3371651
I'm a newbee in C++ and I'm writing a C++ program that asks the user to input two integers and then it raises the first integer to the power specified by the second integer. For example, if the user enters 5 and 8, the result will be 5 subscript 8, i.e., number five will be raised to the eighth power. The program must not use any pre-defined C++ functions (like pow function)for this task. The program should allow the user to perform another calculation if they so desire. Can anyone help
我是 C++ 新手,我正在编写一个 C++ 程序,该程序要求用户输入两个整数,然后将第一个整数提高到第二个整数指定的幂。例如,如果用户输入 5 和 8,结果将是 5 下标 8,即数字 5 将被提升到八次方。程序不得为此任务使用任何预定义的 C++ 函数(如 pow 函数)。如果用户愿意,该程序应该允许用户执行另一个计算。谁能帮忙
回答by turnt
I'm not going to give you any code, because that won't allow you to truly explore this concept. Rather, you should use this pseudo code to implement something on your own.
我不会给你任何代码,因为那不会让你真正探索这个概念。相反,您应该使用这个伪代码来自己实现一些东西。
Create a function which accepts two inputs, the base and the exponent.
创建一个接受两个输入的函数,基数和指数。
Now there are several ways to go about doing this. You can use efficient bit shifting, but let's start simple, shall we?
现在有几种方法可以做到这一点。您可以使用高效的位移位,但让我们从简单开始,好吗?
answer = base
i = 1
while i is less than or equal to exponent
answer = answer * base
return answer
Simply loop through multiplying the base by itself.
只需循环将基数乘以自身即可。
There are other ways that focus on efficiency. Look here to see something that you may want to attempt: are 2^n exponent calculations really less efficient than bit-shifts?
还有其他注重效率的方法。看看这里,看看你可能想尝试的东西:2^n 指数计算真的比位移效率低吗?
回答by π?ντα ?ε?
The program must not use any pre-defined C++ functions (like pow function) for this task
程序不得为此任务使用任何预定义的 C++ 函数(如 pow 函数)
You can use some piece of c++ code like follows, to compute xy, without using any predefined function:
您可以使用如下所示的一些 C++ 代码来计算x y,而无需使用任何预定义函数:
int x = 5;
int y = 3;
int result = 1;
for(int i = 0; i < y; ++i)
{
result *= x;
}
cout << result << endl;
Output:
输出:
125
See a working sample here.
在此处查看工作示例。