1. 程式人生 > >函式_例題:編一函式求1^k+2^k+...n^k的和

函式_例題:編一函式求1^k+2^k+...n^k的和

/*

程式功能:求1^k+2^k+...n^k的和

*/

# include <stdio.h>

double power(int m , int k) /*求m的n次方並返回*/
{
 int i;
 double pw = 1;
 for(i=1; i<=k; ++i) //k代表k次方,比如k=4,i的k次方=i*i*i*i;
  pw*=m;
 return (pw);
}

double sum_power(int k , int n) /*求1到n的k次方的和並返回*/
{
 int i;
 double sum = 0;
 for(i=1; i<=n; ++i)
  sum+=power(i, k);
 return (sum);
}

int main(void)
{
 double sum = 0;
 int k, n;
 printf("input k:");
 scanf("%d", &k);
 printf("\ninput n:");
 scanf("%d", &n);
 sum = sum_power(k, n);
 printf("\n1^%d+2^%d+...%d^%d = %.0lf\n", k,k,n,k,sum);
}

/*

-----------------------------------

input k:4

input n:6

1^4+2^4+...6^4 = 2275

-----------------------------------

*/