#include<stdio.h>
#include<math.h>
float distance(float a,float b,float c,float d);
int main()
{
float x1,y1,x2,y2,dist;
printf("Input x1: ");
scanf("%f", &x1);
printf("Input y1: ");
scanf("%f", &y1);
printf("Input x2: ");
scanf("%f", &x2);
printf("Input y2: ");
scanf("%f", &y2);
distance(x1,x2,y1,y2);
printf("Distance between the given points is: %.2f",sqrt(dist));
return 0;
}
float distance(float a,float b,float c,float d)
{
float x1,x2,y1,y2,dist;
dist=((x2-x1)*(x2-x1) +(y2-y1)*(y2-y1));
return dist;
}
这里输出总是0,不知道为什么。我尝试过将 float 和整数仍然变为 0。
忽略问题的这一部分。 写这篇文章是为了满足发布标准。
最佳答案
需要使用函数调用的返回值
distance(x1,x2,y1,y2);
那就是你需要写的
dist = distance(x1,x2,y1,y2);
否则变量 dist
将仍未初始化并在此语句中使用它
printf("Distance between the given points is: %.2f",sqrt(dist));
导致未定义的行为。
函数distance
不使用其参数a
、b
、c
、d
。相反,它使用未初始化的局部变量 x1
、x2
、y1
、y2
float distance(float a,float b,float c,float d)
{
float x1,x2,y1,y2,dist;
dist=((x2-x1)*(x2-x1) +(y2-y1)*(y2-y1));
return dist;
}
至少写出这样的函数
float distance( float a, float b, float c, float d )
{
return ( b - a ) * ( b - a ) + ( d - c ) * ( d - c );
}
关于c - 为什么我运行c程序后总是得到0?请帮助我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65799855/