首页 > 解决方案 > 想用 fabs 和我自己的绝对值函数求绝对值

问题描述

尝试通过使用库和创建自己的代码来学习函数。我创建了自己的绝对值函数来比较和对比。

预期输入:-10
预期输出:-10 的库绝对值为 10
                 我的 -10 的绝对值是 10

我收到关于 char 和 int 不存在的错误。

#include <stdio.h>
#include <math.h>

int absolute(int a);

int main () {

   int a;

   printf("%d", "Enter a number and I will tell you the absolute value: ");
   scanf("%d", &a);

   printf("The library absolute value of %d is %lf\n", a, fabs(a));
   printf("My absolute value of %d is %lf\n", a, absolute(a));

   return(0);
}

int absolute(int a){
   return a*((2*a+1)%2); 
}

错误:

funcab.c:10:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
    printf("%d", "Enter a number and I will tell you the absolute value: ", a);
funcab.c:14:4: warning: format ‘%lf’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat=]
    printf("My absolute value of %d is %lf\n", a, absolute(a));

标签: c

解决方案


这是不正确的:

printf("%d", "Enter a number and I will tell you the absolute value: ", a);

的第一个参数printf是格式字符串,后面的参数是满足该格式字符串的值。您的格式字符串是 "%d"这意味着您打算打印一个int,但下一个参数是一个字符串。

由于您只想打印一个字符串,因此请采用以下格式:

printf("Enter a number and I will tell you the absolute value: ");

这也是一个问题:

printf("My absolute value of %d is %lf\n", a, absolute(a));

因为%lf格式说明符需要 adoubleabsolute返回int. 由于 的可变性质printfint不会隐式转换为 a double,因此您的格式字符串参数不匹配。您应该%d改用:

printf("My absolute value of %d is %d\n", a, absolute(a));

推荐阅读