C primer plus 第六版 第九章 第八題 程式設計練習答案

Aeron-A發表於2018-06-01

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

相關文章