假设你必须在给定底和高的情况下找到三角形的面积
#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)
解决你的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句