c - 关于数据类型,函数如何在 main() 块之外工作?
问题描述
我是编程新手,想了解如何在 C 中处理函数。给定以下函数
#include <stdio.h>
#include <math.h>
int calc(double m) {
double result = (1 + sqrt(m)) / 2;
return result;
}
int main(void) {
double n;
printf("Enter value for n: ");
scanf("%lf", &n);
printf("Solution of n is: %lf\n", calc(n));
return 0;
}
尝试编译时,它给了我错误:
test.c:15:38: warning: format specifies type 'double' but the argument has type 'int' [-Wformat]
printf("Solution of n is: %lf\n", calc(n));
~~~ ^~~~~~~
%d 1 warning generated.
我不明白,因为我认为我声明了正确的类型!此外,函数本身(函数内部)与 for 之类main
的结果完美配合。但是,如果我在 之外使用该函数,它会给我作为结果(对于我能够编译它的情况)。数据类型有问题,请帮忙!8.02
n = 5
main(void)
8.00
n = 5
解决方案
你的问题是你的函数发回的类型是 aninteger
但你想要一个double
. 您还必须删除多余的}
. 因此,您的函数的结果被转换为整数类型,并且 printf 需要%d
打印整数。
请参阅下面的固定代码:
#include <stdio.h>
#include <math.h>
double calc(double m) {
double result=(1+sqrt(m))/2;
return result;
}
int main(void) {
double n;
printf("Enter value for n: ");
scanf("%lf", &n);
printf("Solution of n is: %lf\n",calc(n));
return 0;
}
推荐阅读
- symfony - Symfony messenger 和 mailer:如何添加 binding_key?
- scala.js - 在 Scala.js 中访问 textarea 值
- testing - 如何在 Gradle 中显示已执行的测试计数摘要?
- swift - 如何根据参数过滤 Firebase 事件?
- java - 什么是强制 Streams.zip 遍历每个元素的最佳方法(使用 Guava,Java)
- java - MyBatis-Spring ManagedTransactionFactory 异常
- python - Pandas 的 df.all 是否有相反的意义?
- android - Android:Roboelectic 测试从 Application.onCreate 引发错误
- amazon-web-services - 限制对 AWS S3 对象的访问
- angular - Spring:授权标头通过 Angular 应用程序始终为空