第9章
第8题:
#include <stdio.h>
void power(double a, int b);
int main(void)
{
double x;
int y;
printf("Please enter two numbers:");
while (scanf("%lf %d",&x,&y) == 2)
{
power(x, y);
printf("\nYou can enter again:");
}
return 0;
}
void power(double a, int b)
{
int i;
if (b == 0 && a != 0)
{
printf("Any number pow zero is 1");
}
if (b < 0)
printf("Please enter an integer that is bigger than zero:");
if (b > 0)
{
for (i = 1; i < b; i++)
{
a *= a;
}
printf("The answer is %lf", a);
}
if (b == 0 && a == 0)
printf("Undefined");
}
第9题 果然是递归。。没做出来 用totur程序跑了一般大致理清,当输入的n值为4, p值为2时,当主函数第一次调用子函数。应为p !=0,n!=0所以跳过前三个if直接来到第4个if,这里n * power(n, p - 1); 第一次调用,返回后 n值为4,p值为2。
接着循环第二次调用n值为16,p值为1,调用后返回16,第三次调用,n值为4*16 =64,p值为0。所以返回pow=1,函数power(doube n, int p)为1,64*1值仍然为64,当pow=2时,返回的结果会是128.
暂时可以强行记忆为,当子函数调用结束后返回主函数,其值为子函数 返回的最后两个值的相乘也就是1*128.
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow;
int exp;
printf("Enter a number and the 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.0;
if ((0 == p) && (0 == n))
{
printf("0 to the 0 undefined, using 1 as the value.\n");
return pow;
}
if (0 == n)
{
pow = 0.0;
return pow;
}
if (0 == p)
{
return pow;
}
if (p > 0)
{
return n * power(n, p - 1);
}
else
{
return power(n, p + 1) / n;
}
}
第10题:
#include <stdio.h>
void to_binary_n(int u, int v);
int main(void)
{
int x, y;
printf("Please enter the number and system you want to transfer:");
while (scanf("%d %d", &x, &y) == 2)
{
to_binary_n(x, y);
printf("\n you can enter again:");
}
return 0;
}
void to_binary_n(int u, int v) #注:这个函数以后应该会用到很多,可以转换进制 需要牢记
{
int r;
r = u % v;
if (u >= v)
{
to_binary_n(u / v, v);
}
printf("%d", r);
}
第11题:
#include<stdio.h>
int fibonacci(int n); #注:函数定义为unsigned long 可以表示的数列更长一些
int main(void)
{
int x;
int reslut;
printf("Please enter how many time you wan to add:");
while (scanf("%d", &x) == 1)
{
reslut = fibonacci(x);
printf("The reslut is %d\n", reslut);
printf("You may enter again:");
}
return 0;
}
int fibonacci(int n)
{
int i;
int a = 1;
int temp=1;
int b;
for (i = 1; i < n; i++)
{
b = a + temp;
a = temp;
temp = b;
}
return a;
}
加油明天第10章了