c - 想用 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));
解决方案
这是不正确的:
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
格式说明符需要 adouble
但absolute
返回int
. 由于 的可变性质printf
,int
不会隐式转换为 a double
,因此您的格式字符串参数不匹配。您应该%d
改用:
printf("My absolute value of %d is %d\n", a, absolute(a));
推荐阅读
- nginx - How add nginx-ingress custom health check behind a nginx reverse proxy
- ruby-on-rails - 无法更新数据库形式的数据
- python - Webscraping with Python and Selenium
- php - 我的 Apache2 RewriteEngine On 和 AllowOverride All 更改是否安全?
- azure - selection of task in release pipeline in azure devops
- c# - Best practice exporting List
in C# for COM Interop - python-3.x - 无法将用户输入插入 MySQL 数据库
- javascript - npm 错误!代码 ELIFECYCLE npm 错误!错误号 2
- java - MySQL查询将多行转换为一行
- ruby - Ruby子类更新父类变量