C Programming - Exercise B

  • Upload
    theo

  • View
    2

  • Download
    1

Embed Size (px)

DESCRIPTION

C Programming - Exercise B

Citation preview

//Exercise #define __STDC_WANT_LIB_EXT1__ 1#define INC 10#define BUF 50#define CPS CLOCKS_PER_SEC#include #include #include #include #include #include #include bool coorRead(char* coor, size_t* length, double* coorSave);int main(void) {double** receiver = NULL;double transmitter[2] = {0.0};double dis = 0.0;double maxdis = -1.0;double* mdisP[2] = {NULL};double pmin = 0.0;double ptrans = 0.0;double power = 0.0;char ans = 'y';unsigned int n = 0;unsigned int c = 0;size_t length = BUF;char coor[length];do {if (c == n) {c += INC;receiver = realloc(receiver, c * sizeof(double*));}*(receiver + n) = calloc(2, sizeof(double));printf("Type %d%s point's coordinates (x%d, y%d): ", n+1, (!n) ? "st" : (n == 1) ? "nd" : (n == 2) ? "rd" : "th", n+1, n+1);gets_s(coor, BUF);fflush(stdin);while(!coorRead(coor, &length, *(receiver + n))) {printf("Please type the coordinates in that form: (x%d, y%d) ", n+1, n+1);gets_s(coor, BUF);fflush(stdin);}n++;if (n > 1) {printf("Do you want to add another point? (yes or no) ");while ((ans = tolower(getchar())) != 'y' && ans != 'n') {fflush(stdin);printf("Please type \"yes\" or \"no\": ");}}fflush(stdin);} while(ans == 'y');for (int i = 0; i < n-1; i++) {for (int j = i+1; j < n; j++) {dis = sqrt(pow((receiver[i][0] - receiver[j][0]), 2.0) + pow((receiver[i][1] - receiver[j][1]), 2.0));if(dis > maxdis) {maxdis = dis;mdisP[0] = receiver[i];mdisP[1] = receiver[j];}}}transmitter[0] = (*mdisP[0] + *(mdisP[0]+1)) / 2.0;transmitter[1] = (*mdisP[1] + *(mdisP[1]+1)) / 2.0;printf("\nType the value for the minimum power (Pmin): ");scanf_s(" %lf", &pmin);ptrans = pmin*maxdis*maxdis;printf("\nTransmitter's coordinates should be: (%.2lf, %.2lf)", transmitter[0], transmitter[1]);printf("\n\nThe transmitters power in order receivers receive %lfW is %.2lf.", pmin, ptrans);for(int i = 0; i < n; i++) {dis = sqrt(pow((receiver[i][0] - transmitter[0]), 2.0) + pow((receiver[i][1] - transmitter[1]), 2.0));power = ptrans/(dis*dis);printf("\nReceiver #%d will receive %.2lf Watt%s.", i+1, power, (power != 1.0) ? "s" : "");}printf("\n\n\tHave a nice day!!!\n\n");clock_t start = clock();while((clock() - start) / CPS < 5);return 0;}bool coorRead(char* coor, size_t* len, double* coorSave) {char del[] = "() ,";char* ptr = NULL;char* pNum1 = strtok_s(coor, len, del, &ptr);char* pNum2 = strtok_s(NULL, len, del, &ptr);if(!pNum1 || !pNum2)return false;*coorSave = atof(pNum1);*(coorSave + 1) = atof(pNum2);return !((!*coorSave && *pNum1 != '0' || !(*coorSave + 1) && *pNum2 != '0'));}