首页 > 解决方案 > 关于数据类型,函数如何在 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.02n = 5main(void)8.00n = 5

标签: ctypes

解决方案


你的问题是你的函数发回的类型是 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;
    
}

推荐阅读