zzk5015377 发表于 2022-1-24 20:37:44

关于abs函数的一点小问题

#include<math.h>
double fun(double x)
{
   double total;

   if(x>10)
   total = log(3*x);

   if(x>1&&x<=10)
   total = sqrt(2*x-1);

   if(x<=1)
   total = abs(x);

   return total;
}
main()
{
printf("fun(12.16)=%8.3f\n",fun(12.16));
printf("fun(6.32)=%8.3f\n",fun(6.32));
printf("fun(-0.32)=%8.3f\n",fun(-0.32));
}
为什么最后这个-0.32打印出来 是 0呢

傻眼貓咪 发表于 2022-1-24 21:20:49

#include <stdio.h>
#include <math.h>
double fun(double x)
{
        double total;

        if (x > 10)
                total = log(3 * x);

        if (x > 1 && x <= 10)
                total = sqrt(2 * x - 1);

        if (x <= 1)
                total = fabs(x); // <----- 注意这里 -----

        return total;
}

int main()
{
        printf("fun(12.16)=%8.3f\n", fun(12.16));
        printf("fun(6.32)=%8.3f\n", fun(6.32));
        printf("fun(-0.32)=%8.3f\n", fun(-0.32));
}
页: [1]
查看完整版本: 关于abs函数的一点小问题