got to write this little program, that reads some points coordinates and do some stuff with it, can't figure out why it doesn't work for more than two points. here is the code:
Code:
#include <stdio.h>#include <stdlib.h>
#include <math.h>
#define DISTANCE sqrt((u[a].x-u[b].x)*(u[a].x-u[b].x)+(u[a].y-u[b].y)*(u[a].y-u[b].y)+(u[a].z-u[b].z)*(u[a].z-u[b].z))
typedef struct{
int x, y, z;
} point;
typedef point* dots;
//building the structures
dots build(int* num) {
int size;
dots Temp;
do{
printf("Type number of points: ");
scanf("%d", &size);
if(size<=0) puts("Invalid Number.");
}while (size<=0);
Temp = (dots) malloc (sizeof(dots)*size);
if (Temp == NULL) exit(1);
*num = size;
return Temp;
}
//reading the points
void readpoints(dots u, int size){ //u stands for Universe
int i;
for(i=0; i<size; i++){
system("cls");
printf("Point %d: ", (i+1));
printf("\nType x coordinate: ");
scanf("%d", &u[i].x);
printf("\nType y coordinate: ");
scanf("%d", &u[i].y);
printf("\nType z coordinate: ");
scanf("%d", &u[i].z);
}
}
//printing the points out
void printp(dots u, int size){
int i;
printf("Typed points:\n");
for(i=0; i<size; i++)
printf("Point %d: {%d, %d, %d}\n", (i+1), u[i].x, u[i].y, u[i].z);
system("PAUSE");
}
//one funcion for both requests, based on choice
void distance(int choice, dots u, int size){
float dis;
if (!choice) {
int a, b;
dis=0;
printf("Type the two points (1 - %d): ", size);
scanf("%d %d", &a, &b);
a--; b--;
dis = DISTANCE;
system("cls");
printf("Distance from %d to %d = %f\n", (a+1), (b+1), dis);
}
else {
int a, b;
for (a=0; a<size; a++){
dis=0;
b=a+1;
dis = DISTANCE;
system("cls");
printf("Distance from %d to %d = %f\n", (a+1), (b+1), dis);
}
}
system("PAUSE");
}
//menu
void menu() {
int choice, num;
dots universe;
printf("First we need some POINTS!\n");
universe = build(&num);
readpoints(universe, num);
do{
system("cls");
printf("Type\n");
printf("1: Retype points.\n");
printf("2: Print typed points.\n");
printf("3: Calculate distance between two points.\n");
printf("4: Calculate distance one by one(1-2, 2-3...)\n");
printf("5: Exit\nChoice: ");
scanf("%d", &choice);
switch (choice){
case 1: universe = build(&num); readpoints(universe, num); break;
case 2: printp(universe, num); break;
case 3:
case 4: distance((choice-3), universe, num); break;
case 5: choice = 0; break;
default: printf("Invalid entry");
system("PAUSE");
choice = 1;
break;
}
}while(choice);
}
//simple main
int main(){
menu();
return 0;
}