繁体   English   中英

将变量传递给C中的函数

[英]Passing variables to functions in C

#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);

}

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

%d作为scanf格式字符串用于int值。 对于float值,您需要%f (或对于double s是%lf )。

格式字符串和指针类型之间的不匹配是“未定义的行为”,并且可能导致所有类型的错误(甚至在某些情况下也可以)。

使用%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 );

尽管看起来好像%d可能代表double,但%d实际上仍用于整数(我喜欢将%d视为digit)。

%f用于浮点数。

%lf用于双%lf类型。 double是浮点数类型,位数是双精度数。 double通常具有64位,float通常为32位。 l是较大类型的长度修饰符。 (我喜欢将其记为“长时间浮动”。)

在不知道“失败”在您的问题中意味着什么的情况下,我将尝试更改scanf语句以使用双格式说明符%lf而不是%d

scanf("%lf", &height);

正如其他人所说,您需要更改您希望从用户那里获取的类型。

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

这应该可以解决问题。 祝你好运M8。

PS“%lf”和“%f”都给您相同的结果。 小数点后六位精度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM