gpt4 book ai didi

c - 将变量传递给 C 中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:20 24 4
gpt4 key购买 nike

#include <stdio.h>
//function prototype
double triangle(double b ,double h);
//main function
int main(void)
{
//declare variables
double height,base, ans;
//take input
printf("Please give the height of the triangle:");
scanf("%d",&height);
printf("Please give the base of the triangle:");
scanf("%d",&base);
//pass variables to triangle function and equal returned value to ans
ans = triangle(base,height);
//prdouble returned doubleeger
system("CLS");
system("COLOR C");
printf("\n\n\t\t\tThe area of the triangle is: %d\n\n\n", ans );
return 0;
}
//area function
double triangle(double b, double h)
{
printf("Hello");
//declare varible
double a;
//process data
a = (b*h)/2;
//return ans to main
return (a);

}

上面是计算三角形面积的程序代码,但当我使用整数时它可以工作,当我尝试使用 double 时它无法运行“三角形”函数。我能得到一些关于为什么会这样的建议吗?

最佳答案

使用%lf 读取double 数字:

scanf("%lf",&height);
scanf("%lf",&base);

使用%f 打印doublefloat 变量:

printf("\n\n\t\t\tThe area of the triangle is: %f\n\n\n", ans );

关于c - 将变量传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746139/

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