从函数返回浮点值

时间:2013-11-23 15:36:11

标签: c function floating-point

嘿,我真的需要帮助这个程序..我不想要一个正确的答案,负面的力量总是返回1 ..谁能帮忙? 该程序应该帮助用户输入基数和功率,并在执行时计算值并显示结果

float square (float a,int b);

int main(){
    int power;
    float base;

    printf("Please input your base number :\n");
    scanf("%f",&base);
    printf("Please input your power :\n");
    scanf("%d",&power);

    float answer = square(base,power);

    printf("Your Result is :\n%f\n",answer);

    system("pause");
    return 0;
}

 float square (float a,int b){
     int counter;
     float total = 1;
     if (b==0){
         return 1;
     } else if (b>0){
         for(counter=0;counter<b;counter++){
             total = total*a;
         }
         return total;
     } else {
         for (counter=0;counter<b;counter++){
             total = total*a;
         }
         total = 1 / total;
         return total;
     }
}

6 个答案:

答案 0 :(得分:2)

total声明为float而非int

此外,您的if's应该在b而不是a

之后,删除所有不必要的(float)演员。

另外,for的最后一次应该向后运行,因为您的初始值小于0

答案 1 :(得分:1)

您的方形函数应如下所示:

float square (float a,int b){
   int counter;
   float total = 1;
   if (b==0){
       return 1;
   } else if (b>0){
       for(counter=0;counter<b;counter++){
           total = (float)total*a;
       }
       return total;
   } else {
       for (counter=0;counter< -b;counter++){
           total = (float)total*a;
       }
       total = 1.0 / (float)total;
       return total;
   }
}

你需要一个浮动总数,你需要检查b而不是if语句中的a,并且当它是负数时你需要计算到-b。

答案 2 :(得分:0)

声明total浮动并将其初始化为

float total = 1.0f;   

使用abs函数处理-ve b

else {
         for (counter=0;counter < abs(b);counter++){
             total = total*a;
     }
     total = 1 / total;
     return total;

}
并包括<stdlib.h> 请参阅工作代码Here

答案 3 :(得分:0)

这部分

 } else {
     for (counter=0;counter<b;counter++){
         total = total*a;
     }
     total = 1 / total;
     return total;
 }

忽略了b是&lt; b = -b;的事实。 0

因此,您应该将 for (counter=0;counter>b;counter--){ total = total / a; } return total; 放入,或

{{1}}

可能会帮到你。

答案 4 :(得分:0)

这可以胜任;)

#include <stdio.h>

#include <math.h>


int main(){
   int power;
   float base;

   printf("Please input your base number :\n");
   scanf("%f",&base);
   printf("Please input your power :\n");
   scanf("%d",&power);

   float answer = pow(base,power);

   printf("Your Result is :\n%f\n",answer);

   system("pause");
   return 0;
}

答案 5 :(得分:0)

这是一个很酷的技巧:

y = a ^ b

ln(y)= b ln(a)

y = exp(b ln(a))

所以函数看起来像这样:

double Power(double a, double b)
{
    return exp(b*log(a));
}
相关问题