c - 为什么我运行c程序后总是得到0?请帮助我

标签 c initialization arguments function-definition

     #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不使用其参数abcd。相反,它使用未初始化的局部变量 x1x2y1y2

    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/

相关文章:

无法将参数存储为数组并在 C 中打印它们

c - 使用 fscanf 从文件中读取单词

c++ - C/C++ - Windows - 如何跟踪 HWND 上下文数据

c - 如何在 Ascii 中进行数学运算?

c - C中的结构数组初始化

c++ - 成员变量作为默认参数?

r - 对 R 术语 : Attributes, 参数和参数感到困惑

c++ - 在 extern C 中使用 _attribute__ ((nothrow)) 有意义吗?

c++ - 为什么编译器不能像在变量声明中那样在结构成员中设置 char[] = { .. } 的大小?

swift - 如何在 Swift 中使用反射获取所有类初始化器