题目:平面坐标系中有一只蚂蚁,它从第1个点出发,按照直线爬行到第2个点,再从第2个点按照直线爬行到第3个点,……,直到爬到最后一个点。请你编程算出蚂蚁的总的爬行距离 输入 输出 样例输入 程序代码: }; |
|
把代码写得清晰点,哪怕繁琐一点也不要紧,让自己在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%以上! |