C语言 C - 在不使用 Pow 的情况下为指数编写函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15265230/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:36:17 来源:igfitidea点击:
C - Writing a function for an exponent without using Pow
提问by Americo
I have this program:
我有这个程序:
#include <stdio.h>
long int x_to_the_n (int x,int n)
{
int i;
int number;
int i;
int i = 1;
for (i = 0; i < n; ++i)
x = x*x;
return(number);
}
int main()
{
int number;
int exponent;
int answer;
printf ("Enter a number: ");
scanf ("%i", &number);
printf ("Enter a number that represents the power you want your number to be raised to: ");
scanf ("%i", &exponent);
answer = x_to_the_n(number,exponent);
printf("X To The N is %li",answer);
return 0;
}
Right now, the function x_to_the_n is not correctly equating x ^ n...I was wondering if anyone had suggestions to calculate x to the n without using the c pow library function.
现在,函数 x_to_the_n 没有正确地等同于 x ^ n ...我想知道是否有人建议在不使用 c pow 库函数的情况下计算 x 到 n。
回答by niculare
Try this:
尝试这个:
long int x_to_the_n (int x,int n)
{
int i; /* Variable used in loop counter */
int number = 1;
for (i = 0; i < n; ++i)
number *= x;
return(number);
}

