结构体初步,我应该是后面算走过的总路程错了

C语言 码拜 9年前 (2015-05-11) 1258次浏览 0个评论

题目:平面坐标系中有一只蚂蚁,它从第1个点出发,按照直线爬行到第2个点,再从第2个点按照直线爬行到第3个点,……,直到爬到最后一个点。请你编程算出蚂蚁的总的爬行距离

输入
第1行是一个整数,表示点的个数
接下来是n行,每行2个整数,表示n个点的坐标。

输出
蚂蚁的总爬行距离

样例输入
3
0 0
0 3
4 0
样例输出
8.00

程序代码:
#include <stdio.h>
#include <math.h>
struct POINT
{    
    int x;
    int y;

};
int N;//点的个数 
void getpoint(struct POINT *p,int num);
float getdistance(struct POINT *p,int num);
main()
{   int i;
    struct POINT point[60];
    float distance;
    scanf(“%d”,&N);
    getpoint(point,N);
    distance=getdistance(point,N);
    printf(“%.2f”,distance);   
}
void getpoint(struct POINT *p,int num)
{    int i;
    for(i=0;i<num;i++)
    {
     scanf(“%f %f”,&p[i].x,&p[i].y);    
     
     }    
}
float getdistance(struct POINT *p,int num)
{
    int i;
    float sum=0;
    for(i=1;i<num+1;i++)
    {
        sum=sum+sqrt((p[i].x-p[i-1].x)*(p[i].x-p[i-1].x)+(p[i].y-p[i-1].y)*(p[i].y-p[i-1].y));    
    }
    return sum;
    
}

把代码写得清晰点,哪怕繁琐一点也不要紧,让自己在debug时更方便

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct tagPoint
{
	int x;
	int y;
} Point;

typedef struct tagPath
{
	Point CurrentPoint;
	struct tagPath * Next;
} *Path, PathNode;

double DistanceBetween(const Point p1, const Point p2)
{
	const int dx = p1.x - p2.x;
	const int dy = p1.y - p2.y;
	return sqrt(dx * dx + dy * dy);
}

void ReadNode(PathNode * node)
{
	scanf("%d%d", &node->CurrentPoint.x, &node->CurrentPoint.y);
	node->Next = NULL;
}

Path MakePath(int num)
{
	PathNode fakehead = {{0, 0}, NULL};
	Path * ret = &fakehead.Next;
	PathNode * cur = &fakehead;
	while (num --> 0)
	{
		cur->Next = (PathNode*)malloc(sizeof(PathNode));
		cur = cur->Next;
		ReadNode(cur);
	}
	return *ret;
}

void DeletePath(Path path)
{
	while (path)
	{
		Path next = path->Next;
		free(path);
		path = next;
	}
}

double PathLength(const Path path)
{
	double result = 0;
	Path p = path;
	while (p->Next)
	{
		result += DistanceBetween(p->CurrentPoint, p->Next->CurrentPoint);
		p = p->Next;
	}
	return result;
}

int main(void)
{
	int num = 0;
	scanf("%d", &num);
	Path path = MakePath(num);
	printf("%f", PathLength(path));
	DeletePath(path);
	return 0;
}
40分
2个问题 
1) scanf(“%f %f”,&p[i].x,&p[i].y);  要么把xy的定义为float,或者把%f改为%d
2) for(i=1;i<num+1;i++) 应该为i<num, i的值不能取到n
printf里面的%和变量的一一对应关系
scanf里面的%和变量以及变量前加不加&的一一对应关系
是C代码中非常容易出错的地方,而且通常编译还不出错。
所以在编译源代码之前值得专门仔细检查一遍甚至多遍。

“多一少一”问题占程序员常犯错误的10%以上!
避免“多一少一”问题的方法之一是将比如<10甚至<5的数代入程序片断,搬手指头心算验证一下程序到底应该写为
x、x-1、x+1中的哪个?
<、<=、==、>、>=中的哪个?


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明结构体初步,我应该是后面算走过的总路程错了
喜欢 (1)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!