2013-02-05 31 views
0

我有一個函數可以計算雙數的功率,下一個任務是添加選項,以便處理負功率。在C中加倍返回負功率C

所以我加入這個代碼的功能:

if (p < 0) 
    { 
     for (y = 1; y <= p; y++) 
     { 
      pow *= n; 
     } 
     pow = 1/pow; 
    } 

整個程序很短,所以我會太分享:

#include <stdio.h> 
double power(double n, int p); // ANSI prototype 

int main(void) 

{ 
    double x, xpow; 
    signed 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); // function call 
     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, signed int p) // function definition 
{ 
    double pow = 1; 
    int i; 
    int y; 

    if (p < 0) 
    { 
     for (y = 1; y <= p; y++) 
     { 
      pow *= n; 
     } 
     pow = 1/pow; 
    } 


    for (i = 1; i <= p; i++) 
     pow *= n; 

    return pow; // return the value of pow 
} 

,如果im進入輸入5.0和電源-3我假設得到0.008,即時獲取1 ...

回答

1

你忘了其他嗎?對於如果

if (p < 0) 
{ 
    for (y = 1; y <= -p; y++) 
    { 
     pow *= n; 
    } 
    pow = 1/pow; 
} 
else 

for (i = 1; i <= p; i++) 
    pow *= n; 
0

如果你輸入-3的權力,你的任何條件都不會成立。

if (p < 0) 
    { 
     for (y = 1; y <= p; y++) 
     { 
      pow *= n; 
     } 
     pow = 1/pow; 
    } 

如果p < 0,y永遠不會小於p。

+0

right ...:/謝謝@Falmarri – MNY