C primer plus 第六版 第九章 第八题 编程练习答案

版权声明:转载请注明来源~ https://blog.csdn.net/Lth_1571138383/article/details/80536257

Github 地址:这里这里φ(>ω<*)

/*

    本程序应 习题-8 建立。
  题目要求: 程序清单第六章 6.20 ,改进power() 函数,使其能正确计算负幂。
               另外,函数要处理 0 的任何幂都为 0 ,任何数的 0 次幂都为 1。
     (函数应报告 0 的 0次幂未定义, 因此把该值处理为1)。
    要使用一次循环,应在程序中测试该函数。
*/




#include<stdio.h>


double power(double x, int y);


int main(void)
{
double value = 0;
double f = 0;
int m = 0;


printf("Enter a number and to positive integer power to which.\n");
printf("The number will be raised. Enter q to quit.\n");
printf("Now, please enter number :");


while (scanf_s("%lf%d", &value, &m) == 2)
{


f = power(value, m);


if (f == 0)
{
printf("Please input again :");
continue;
}
else
{
// 空语句。
;
}
printf("%.3g to the power %d is %.5g \n\n", value, m, f);
printf("Enter next pair of numbers or q to quit :");
}


printf("Bye !\n");


return 0;
}


double power(double x, int y)
{
double one = 1;   // 计算负幂用。
int i = 0;           // 循环用。


double count = 1;    // 保存计算幂结果。


if (x == 0 && y == 0)
{
// 在指数为 0 , 0 次幂的情况下。报告 0 的 0 次幂未定义,把该值处理为 1。
}
else if (x == 0)
{
// 在指数为 0 时,报告 0 的任何次幂都为 0。
printf("0 的任何次幂都为 0, 请重新输入。\n");
}
else if (y == 0)
{
// 在幂为 0 的情况下, 报告任何数的0次幂都为1。
printf("任何数的0次幂都为1, 请重新输入。\n");
}
else
{
// 空语句。
;
}


for (i = 0; i < y; i++)
{
count *= x;
}


if (x < 0)
{
// 在指数小于0的情况下,即为负数。则进行负幂计算。 
// (负幂计算即为 x的y次幂 求其幂的倒数即可得出。 )
count = one / count;
}
else
{
// 空语句。
;
}


return count;
}

猜你喜欢

转载自blog.csdn.net/Lth_1571138383/article/details/80536257