为什么一个输出0而另一个输出正确答案?

Why is the output 0 in one but the correct answer in the other?

假设你必须在给定底和高的情况下求出三角形的面积

#include <stdio.h>
int main ()
{
    float base,height,area;
    printf("Enter base and height of triangle: \n");
    scanf("%f%f",&base,&height);
    area=0.5*base*height;
    printf("The area of the triangle is %f",area);
    return 0;
}

为什么程序用上面的代码给出了正确的答案,而用下面的代码却没有??

#include <stdio.h>
int main ()
{
    float base,height,area;
    printf("Enter base and height of triangle: \n");
    scanf("%f%f",&base,&height);
    area=(1/2)*base*height;
    printf("The area of the triangle is %f",area);
    return 0;
}

无论您输入什么值,这个都显示 0。我在这里缺少什么明显的东西?

表达式

(1/2)

两个整数相除。与 python 或其他几种语言相反,这不会隐式转换为浮点数,而是保持为整数。因此,结果为 0.

将表达式更改为

(1./2)

解决了您的问题。