如何输出C中浮点函数返回的值

时间:2017-04-30 02:13:51

标签: c function

问题是我必须提示用户输入三角形的基数和高度作为浮点数,也将它传递给函数,函数将获得三角形的区域,将其返回到main。问题是该区域的输出是0.000000。

它也给了我一个警告

Severity    Code    Description Project File    Line    Suppression State
Warning C4477   'printf' : format string '%f' requires an argument of type 'double', but variadic argument 1 has type 'float (__cdecl *)(float,float)'  line 38. 

我做错了什么?

    #include <stdio.h>
    #include <stdlib.h>


float area(float base,float height);


int main()
{   

float height;
printf("Enter an height: ");
scanf_s("%f", &height);
printf("Number = %f", height);

float base;
printf("Enter an base: ");
scanf_s("%f", &base);
printf("Number = %f", base);

area(height, base);

printf("area of triangle : %f\n", area);

return 0;

}

float area(float base, float height)
{

float half = .5;
float area = half * base * height;

return area;

}

2 个答案:

答案 0 :(得分:2)

您的主要问题是您正在传递函数(area),而不是函数调用的结果(area(height, base))。您需要将结果存储到变量中,然后打印该变量。

float computedArea = area(height, base);
printf("area of triangle : %f\n", computedArea);

或者你可以在这种情况下调用就地功能,因为它不会使线路太长:

printf("area of triangle : %f\n", area(height, base));

以下是我将如何编写此代码:

#include <stdio.h>
#include <stdlib.h>

double area(double base,double height);

int main() {  
    printf("Enter the height: ");
    double height;
    scanf("%lf", &height);
    printf("Height: %f\n", height);

    printf("Enter the base: ");
    double base;
    scanf("%lf", &base);
    printf("Base: %f\n", base);

    double computedArea = area(height, base);

    printf("Triangle Area: %f\n", computedArea);
    return 0;
}

double area(double base, double height) {
    return (base * height) / 2.0;
}

答案 1 :(得分:0)

更改

area(height, base); // invoking a function without capturing its output

printf("area of triangle : %f\n", area); // area refers to the memory location where the function resides.

printf("area of triangle : %.2f\n", area(height, base));
 // Directly passing the area output to printf. The '.2' specifies the precision you want