#include <stdio.h>
double power(double n, int p); // ANSI函数原型
int main(void){
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2){
xpow = power(x, exp); // 函数调用
printf("%.3g to the power %d is %.5g\n", x, exp,xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, int p) // 函数定义{
double pow = 1;
int i;
for (i = 1; i <= p; i++)
pow *= n;
return pow; // 返回pow的值
}
改进以上函数,使其能正确计算负幂。另外,函数要处理0的任何次幂都为0,任何数的0次幂都为1(函数应报告0的0次幂未定义, 因此把该值处理为1)。要使用一个循环,并在程序中测试该函数。
#include <stdio.h>
double power(double n, int p); // ANSI函数原型
int main(void){
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2){
xpow = power(x, exp); // 函数调用
printf("%.3g to the power %d is %.5g\n", x, exp,xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, int p){
double pow = 1;
if(n!=0){
if(p>0){
int i;
for (i = 1; i <= p; i++){
pow *= n;
}
return pow;
}
else if(p<0){
int i;
for (i = 1; i <= (-p); i++){
pow *= n;
}
pow=1/pow;
return pow;
}
else
return 1;
}
else
return 0;
}
使用递归函数重写上述代码
#include<stdio.h>
double power(double n, int p);
int main(){
double n;
int p;
int c;
while(1){
printf("Enter the value of the number and its power that you want to calculate(enter 'q' to quit):");
c=scanf("%lf %d",&n,&p);
if(c!=2)
return 0;
else{
printf("The value you want is:%lf \n\n",power(n,p));
}
}
}
double power(double n, int p){
double pow = 1;
if(n!=0){
if(p>0){
pow=n*power(n,p-1);
return pow;
}
else if(p<0){
p=-p;
pow=n*power(n,p-1);
pow=1/pow;
return pow;
}
else
return 1;
}
else
return 0;
}
标签:函数,power,8.9,double,Enter,int,exp,printf,cpp
From: https://blog.csdn.net/2403_87560502/article/details/143472443