-3

我有这个程序:

#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;
}

现在,函数 x_to_the_n 没有正确地等同于 x ^ n ...我想知道是否有人建议在不使用 c pow 库函数的情况下计算 x 到 n。

4

1 回答 1

10

试试这个:

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);
}
于 2013-03-07T07:20:04.100 回答