gpt4 book ai didi

c - 如何输出由C中的float函数返回的值

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:43 25 4
gpt4 key购买 nike

问题是我必须提示用户输入三角形的底边和高度作为 float ,也将它传递给一个函数,该函数将获取三角形的面积,将其返回给 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;

}

最佳答案

您的主要问题是您传递的是函数 (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;
}

关于c - 如何输出由C中的float函数返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com