我需要一些关于这个C程序的快速帮助我正试图运行。它编译并运行但在某处有逻辑错误。显示距离时,它会显示一些大数字(全部相同,如2117900),而不是正确的数字。没有调试器,我不知道如何找到错误。我精通C#和Java,但C对我来说有点挣扎。希望有人能找到逻辑错误。此外,我所看到的代码中的任何提示,特别是关于指针的提示,将不胜感激!
point.c文件:
#include <assert.h>
#include <stdio.h>
#include "point.h"
#include <math.h>
/*
* Update *p by increasing p->x by x and
* p->y by y
*/
void point_translate(Point *p, double x, double y)
{
p = point_set(p,(point_getX(p)+x),(point_getY(p)+y));
}
/*
* Return the distance from p1 to p2
*/
double point_distance(const Point *p1, const Point *p2)
{
double temp1 = (point_getX(p1) - point_getX(p2));
double temp2 = (point_getY(p1) - point_getY(p2));
double temp3 = (temp1*temp1)+(temp2*temp2);
double dist = sqrt(temp3);
return dist;
}
point.h文件:
#include <math.h>
#ifndef _POINT_H_
#define _POINT_H_
/*
* Simplistic definition of point and operations on
* a point for 2D double-precision space.
*/
typedef struct PointStruct
{
double x;
double y;
} Point;
void point_translate(Point *p, double x, double y);
double point_distance(const Point *p1, const Point *p2);
static inline double point_getX(const Point *p)
{
return p->x;
}
static inline double point_getY(const Point *p)
{
return p->y;
}
static inline Point *point_set(Point *p, double x, double y)
{
p->x = x;
p->y = y;
return p;
}
#endif
testPoint.c文件:
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "point.h"
int main(int argc, char **argv)
{
Point p1;
point_set(&p1, 1.0, 1.0);
double distance;
Point *p2 = malloc(sizeof(Point));
assert(p2);
point_set(p2, 1.0, 1.0);
distance = point_distance(&p1, p2);
printf("The distance is: %d\n",distance);
point_translate(&p1, 1.0, 0.0);
distance = point_distance(&p1, p2);
printf("The distance is: %d\n",distance);
point_set(&p1, 0.0, 0.0);
point_set(p2, 3.0, 4.0);
distance = point_distance(&p1, p2);
printf("The distance is: %d\n",distance);
free(p2);
p2 = NULL;
printf("OK\n");
return 0;
}
答案 0 :(得分:2)
使用printf
和类似函数时,必须小心将格式说明符与正确的数据类型进行匹配。 "%d"
期望参数类型为int
,但您的参数类型为double
。 "%g"
是double
参数的一个很好的默认说明符。