想要使用晶圆厂和我自己的绝对值函数查找绝对值

时间:2018-11-05 16:29:54

标签: c

尝试通过玩转库并创建自己的代码来学习功能。我创建了自己的绝对值函数来进行比较和对比。

expected input: -10
expected output: The library absolute value of -10 is 10
                 My absolute value of -10 is 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));

1 个答案:

答案 0 :(得分:1)

这是不正确的:

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格式说明符期望使用double,但是absolute返回int。由于printf的随机性,int不会隐式转换为double,因此格式字符串参数不匹配。您应该改用%d

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