0

I have to find out n equi-spaced points on boundary of an ellipse when a (semimajor axis) and b (semiminor axis) are given. Starting point is considered as (a, 0). The formula given in code is used to find out such points.

#include <stdio.h>
#include <math.h>
#define PI 3.142

 int main()
 {
     int n, i, a, b;
     double dt, x[20], y[20];

   printf("Enter semimajor axis:- ");
   scanf("%d", &a);
   printf("Enter semiminor axis:- ");
   scanf("%d", &b);

   printf("Enter no of points to be equi-spaced:- ");
   scanf("%d", &n);

   //Starting point is:- (a, 0). So x[0] = a and y[0] = 0
   x[0] = a;
   y[0] = 0;

   dt = (2*PI)/n;
  for (i=0; i<n; i++)
  {
        x[i+1] = x[i]*cos(dt) - (a/b)*y[i]*sin(dt);
        y[i+1] = (b/a)*x[i]*sin(dt) + y[i]*cos(dt);
  }
  printf("\n");
  for (i=0; i<n; i++)
  {
       printf("%lf, %lf\n", x[i], y[i]);
  }
 }

Input:- Enter semimajor axis:- 4\n Enter semiminor axis:- 3\n Enter no of points to be equi-spaced:- 4

Output:- 4.000000, 0.000000\n -0.000815, 0.000000\n 0.000000, -0.000000\n -0.000000, 0.000000

This is not expected output.

CKJ_1630
  • 33
  • 4
  • 1
    Don't define your own pi. You're already including math.h, so just use `M_PI`, which is far more accurate. (I'm not sure if `M_PI` is available on all implementations, but it should be available in gcc.) – Tom Karzes Aug 07 '23 at 14:10
  • Integer division such as your `(a/b)` truncates towards 0 to the nearest integer. – Ian Abbott Aug 07 '23 at 14:11
  • 1
    You might as well declare `a` and `b` as type `double` and use `scanf("%lf", &a);` to read `a` as a `double`, and do the same for `b`. If you really must declare `a` and `b` as integers, you will need to use `((double)a/b)` and `((double)b/a)` to calculate the fractions. – Ian Abbott Aug 07 '23 at 14:23
  • see [OpenGL Ellipse with start/end angle issues](https://stackoverflow.com/a/71219436/2521214) especially `[Edit2] Fast analytic O(1) solution` for some inspiration – Spektre Aug 10 '23 at 06:54

0 Answers0