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

标签 c function variables

#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/

相关文章:

Javascript:脚本在函数调用时终止

function - LISP:以谓词作为参数

c - gdb 中 backtrace(backtrace_symbols) 和 bt 的区别

c - 为什么该程序不提供 float 和 double 数据类型的输出?

javascript - 在html中打印JS文件的结果

c++ - C++ 中的类中可以有可变数量的变量吗?

c++ - 从输入中读取两个值并将它们相加,仅使用一个变量.. 可能吗?

c - 如何实现具有优先级和结合性的中缀计算器

c - 有没有办法测试无效的内存位置?

r - R 中的模型语法 : how to input dynamic variables?