Advertisement
MadBromance

C - Polygonberechnung (ohne Aufgabe 4)

Dec 8th, 2019
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1.  
  2. #define _CRT_SECURE_NO_WARNINGS
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <math.h>
  7.  
  8.  
  9. int main()
  10. {
  11. double flaecheninhalt;
  12.  
  13. // variables for reading the measurements from file
  14. FILE * fp;
  15. size_t len = 0;
  16. char resp;
  17.  
  18. double x, y;
  19.  
  20. // open the input file "messwerte.txt" for reading
  21. fp = fopen("polygon.txt", "r");
  22. if (fp == NULL)
  23. {
  24. // if file could not be opened (wrong path, not readable, ...)
  25. // output a short message and immediately exit
  26. printf("Eingabedatei kann nicht geoeffnet werden.\n");
  27. scanf("%c", &resp);
  28. exit(EXIT_FAILURE);
  29. }
  30.  
  31. // print program header
  32. printf("\n\nProgramm zur Berechnung eines Polygons\n");
  33. printf("--------------------------------------------------------\n");
  34.  
  35. // the following loop reads a new value in every iteration
  36. // until the end of the file or some invalid token is found
  37. int n=0;
  38. int a[999];
  39. int b[999];
  40.  
  41. while (1)
  42. {
  43. len = fscanf(fp, "%lf %lf", &x, &y);
  44.  
  45. if (len == EOF)
  46. break;
  47. else if (len == 0) {
  48. printf("Unerwartetes Zeichen in der Eingabedatei.");
  49. scanf("%c", &resp);
  50. exit(EXIT_FAILURE);
  51. }
  52.  
  53. printf("Lese Eckpunkt: %6.2f/%6.2f\n", x, y);
  54. a[n] = x;
  55. b[n] = y;
  56. n++;
  57. }
  58.  
  59. flaecheninhalt=0;
  60.  
  61. for(int i=0; i<n;i++){
  62. if(i==(n-1)){
  63. flaecheninhalt +=((b[i]+b[0])*(a[i]-a[0]));
  64.  
  65. }
  66. else{
  67. flaecheninhalt += ((b[i]+b[i+1])*(a[i]-a[i+1]));
  68. }
  69. }
  70. flaecheninhalt = flaecheninhalt/2;
  71. double xschwer, yschwer;
  72. for(int j=0;j<n;j++){
  73. if(j==(n-1)){
  74. xschwer += (a[j] + a[0]) * (a[j] * b[0] - a[0] * b[j]);
  75. yschwer += (b[j] + b[0]) * (a[j] * b[0] - a[0] * b[j]);
  76.  
  77. }
  78. else {
  79. xschwer += (a[j] + a[j + 1]) * (a[j] * b[j + 1] - a[j + 1] * b[j]);
  80. yschwer += (b[j] + b[j + 1]) * (a[j] * b[j + 1] - a[j + 1] * b[j]);
  81. }
  82. }
  83. xschwer = xschwer / (6*flaecheninhalt);
  84. yschwer = yschwer / (6*flaecheninhalt);
  85.  
  86.  
  87. // output results
  88. printf("\nErgebnisse:\n");
  89. printf("-----------\n\n");
  90. printf("A = %.2f\n", flaecheninhalt);
  91. printf("Schwerpunkt = (%.2f|%.2f) \n", xschwer, yschwer);
  92.  
  93. // finally close the input file and clean up memory
  94. fclose(fp);
  95.  
  96. // wait for user input before closing terminal
  97. scanf("%c", &resp);
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement