Opgaver i denne lektion   Gå til annoteret slide, hvor denne opgave er tilknyttet -- Tastaturgenvej: 'u'   Alfabetisk indeks   Kursets hjemmeside   

Opgaveløsning:
Inden i eller uden for en cirkel


Her er et muligt program, der løser opgaven:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DELTA 0.000001

int main(void){
  double r = 0.0, x = 0.0, y = 0.0;

  /* Prompt for input: */
  printf("Enter radius, x, and y:\n");
  scanf(" %lf %lf %lf", &r, &x, &y);

  if (fabs(x*x + y*y - r*r) < DELTA)
    printf("The point (%1.4f,%1.4f) is on the circle\n", x, y);
  else if (x*x + y*y < r*r)
    printf("The point (%1.4f,%1.4f) is inside the circle\n", x, y);
  else
    printf("The point (%1.4f,%1.4f) is outside the circle\n", x, y);

  return EXIT_SUCCESS;
}

Her er en udgave som kun har print-detaljerne én gang, og som gør brug af nogle logiske assignments (til on-circle, inside og outside):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DELTA 0.000001

int main(void){
  double r = 0.0, x = 0.0, y = 0.0;
  int inside = 0, on_circle = 0, outside = 0;

  /* Prompt for input: */
  printf("Enter radius, x, and y:\n");
  scanf(" %lf %lf %lf", &r, &x, &y);

  /* Calculate inside, on circle, or outside */
  on_circle = fabs(x*x + y*y - r*r) < DELTA;
  inside = x*x + y*y < r*r;
  outside = !(inside || on_circle);

  /* Print results: */
  printf("The point (%1.4f,%1.4f) is %s with center point (0,0).\n",
         x, y, 
         on_circle ? "on circle" : inside ? "inside circle" : "outside circle");
  
  return EXIT_SUCCESS;
}