C bootcamp · Lab 12

Point distance

mediumStructures15 minLesson: Structures

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

A Point has integer fields x and y. Read four integers: x1 y1 x2 y2.

Print the Euclidean distance between the two points, rounded to two decimal places.

distance = sqrt((x2 - x1)² + (y2 - y1)²)

Input. Four integers: x1 y1 x2 y2.

Output. One number with two decimal places, for example 5.00

Constraints

  • -100 ≤ each coordinate ≤ 100
  • Use math.h and printf("%.2f\n", d).

Examples

Example 1 — A 3-4-5 triangle.
Input
0 0 3 4
Output
5.00
Example 2
Input
1 1 1 1
Output
0.00
Hint
  1. Store the points in struct Point { int x; int y; };
  2. dx and dy can stay ints. Cast to double before sqrt, or multiply in double.
Show correct code

Peek only after you have tried. You can still Check your own version.

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

struct Point {
  int x;
  int y;
};

int main(void) {
  struct Point a, b;
  if (scanf("%d %d %d %d", &a.x, &a.y, &b.x, &b.y) == 4) {
    double dx = b.x - a.x;
    double dy = b.y - a.y;
    printf("%.2f\n", sqrt(dx * dx + dy * dy));
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.