How to calculate the distance in fewer lines?

Asked

Viewed 189 times

0

I have this exercise on C to calculate the distance between two points using structs, but he repeats the point code a lot, to x and y, how to do it in fewer lines or use array?

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

typedef struct {
    int x;
    int y;
} ponto;
int main() {

    ponto p1;
    printf("Digite o ponto p1(X): ");
    scanf("%d", &p1.x);

    printf("Digite o ponto p1(Y): ");
    scanf("%d", &p1.y);

    ponto p2;
    printf("Digite o ponto p2(X): ");
    scanf("%d", &p2.x);

    printf("Digite o ponto p2(Y): ");
    scanf("%d", &p2.y);

    /*Formula para calcular distancia entre dois pontos
     * d = sqrt((p2 x - p1 x)² + (p2 y - p1 y)²)
     */

     float distancia = sqrt((pow(p2.x - p1.x, 2)) + ((pow(p2.y - p1.y, 2))));
     printf("Resultado: %.2f", distancia);

     return 0;
}
  • I could do it, but I’ll just give you a few ways. When a code repeats too much something is wrong, or the code could be improved, this is your case. Try to separate the reading of data, create a method where you send the struct by reference, Ole as you will display the text to the user is quite easy and you can!

2 answers

7


Without doing very crazy things and damaging the readability, there is very little that can be done. You can declare the two variables on the same line, reduce the blank lines and unnecessary comments, delete the #include without use and delete the variable that is not required, as well as removing unnecessary parentheses.

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

typedef struct {
    int x;
    int y;
} ponto;
int main() {
    ponto p1, p2;
    printf("Digite o ponto p1(X): ");
    scanf("%d", &p1.x);
    printf("Digite o ponto p1(Y): ");
    scanf("%d", &p1.y);
    printf("Digite o ponto p2(X): ");
    scanf("%d", &p2.x);
    printf("Digite o ponto p2(Y): ");
    scanf("%d", &p2.y);
    printf("Resultado: %.2f", sqrt(pow(p2.x - p1.x, 2) + (pow(p2.y - p1.y, 2))));
}

Otherwise I don’t know if I want to change the structure of the code. I don’t know what the requirements are. It is possible to make a loop to reduce it further. It is possible to create a function to handle the loading of the two points.

You can reduce code size and increase complexity. Pays off? You’re prepared to deal with this complexity?

If you want, as shown in the comments below, then you can do it this way:

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

typedef struct {
    int x;
    int y;
} ponto;
int quadradoPontos(int p1, int p2) {
    return pow(p2 - p1, 2);
}
void lePonto(char nome, char coordenada, ponto *p) {
    printf("\nDigite o ponto p%c(%c): ", nome, coordenada);
    if (coordenada == 'X') {
        scanf("%d", &p->x);
    } else {
        scanf("%d", &p->y);
    }
}
int main() {
    ponto p1, p2;
    lePonto('1', 'X', &p1);
    lePonto('1', 'Y', &p1);
    lePonto('2', 'X', &p2);
    lePonto('2', 'Y', &p2);
    printf("\nResultado: %.2f", sqrt(quadradoPontos(p1.x, p2.x) + quadradoPontos(p1.y, p2.y)));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Did it get simpler? No. Did it get shorter? No. If it was an exercise about creating a function, okay. But then it should be in the question. I should post how I had tried to do the job, what problems I was having with it. The question would be another.

Obviously if you pass wrong arguments to the function, it will all go wrong. What is the advantage of doing this if not an example of creating a function? None. Even if it is an example of a function, it has better examples, it only teaches to increase complexity and make the code less robust. All this because there was no repetition of any code. It had an appearance of repetition, but not actual repetition. What was done has nothing to do with DRY, that it would be something effect, quite the contrary.

I had to create 3 extra variables and 2 flow deviations, one of them remote to the main code, which makes it difficult to follow the flow, and I had to parameterize something I didn’t need. This is called complexity.

It could do in different ways, it could have two or four functions to write on the screen and ask for data. Would it help in something? It would decrease complexity, but increase "repetition". The function that computes the square could eliminate some of the "repetition" and could pass the points to and solve there within the function which coordinate to use. This getting more complex, needless, arguable gain (actually for experienced programmers there is no discussion of which is worse).

Rethink your concept of repetition, legibility must come first: KISS.

  • Of course, it will not increase complexity and you can reuse the code. OO principle.

  • 4

    First: Ahh, OO? What are you talking about? Object orientation in C? OO in a simple example of a silly calculation that is an exercise? I imagined some crazy things, but proposing O in a code like this is one that I never imagined anyone would propose. But a simple loop would make the code more complex. It would have to use extra variables, control the flow, to gain a few lines. In fact, I think it would not even gain lines, if bobear would get bigger. Before getting dazzled in OO begin to understand what is complexity. It is not a matter of opinion. There is formal definition about this.

  • I wanted to use a function, I declared so: void ler(point *p) { scanf("%d", p->x), but gives an error.

  • @user46084 The question is Como fazer em menos linhas?. It does not speak in function. If you still want to use a function, you will probably have more lines. This is not even in the code posted. You have to write in the question what you really want, I answered what is written on it. If you wanted something else, the question should be closed because it is not clear.

  • Worked out was not using this & function, but becomes more readable

  • But, you just haven’t removed the comments and the distance variable? , could be using function.

  • 1

    @user46084 yes, could, but your question does not speak of any of this. I will put in the answer as you want, but I am going beyond what the question asks.

  • 3

    +1. Good demonstration (and explanation) of a typical case where it was best to leave everything as it was, that there was no problem at all.

  • This lot of printf and scanf leaves the code very repeatedooo.

  • 2

    @user46084 There is no repetition. I get the impression that you have a worse OCD than mine :) . Each line is semantically different from the other. If one day you become a programmer, you will understand that the first code is much better. Repetition only runs when all tokens are equal, this is not the case. Because of this, I had to create various devices to resolve this irregularity. There are situations that make up for doing this, this is not one of them. Note that the bottom code is full of repetition as well, according to your criteria. Try to fix this.

  • 3

    @user46084 to program is better to focus more on technique than on these aesthetic "emotions". Aesthetics in the code is equal design: it is valuable, but only good if the form joins the function.

  • But it’s because the exercise is very simple

  • 1

    @user46084 it was to be very simple, it became complex. And precisely because it is something very simple should not complicate. If you had a real reason to do all this, okay, no problem, but you don’t. Who complicates the simple, destroys the complicated.

Show 8 more comments

2

Only to complement the another answer, you can use the function hypot, defined (also) in the header math.h.

View documentation.

This function basically returns the square root of the sum of the squares of the two given numbers. In other words, returns the hypotenuse (hypotenuse) rectangular triangle.

See, instead of:

sqrt(pow(p2.x - p1.x, 2) + (pow(p2.y - p1.y, 2)))

Can do:

hypot(p2.x - p1.x, p2.y - p1.y)

Thus:

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

typedef struct {
  int x;
  int y;
} ponto;

int main() {
  ponto p1, p2;
  printf("Digite o ponto p1(X): ");
  scanf("%d", &p1.x);
  printf("Digite o ponto p1(Y): ");
  scanf("%d", &p1.y);
  printf("Digite o ponto p2(X): ");
  scanf("%d", &p2.x);
  printf("Digite o ponto p2(Y): ");
  scanf("%d", &p2.y);

  printf("Resultado: %.2f\n", hypot(p2.x - p1.x, p2.y - p1.y));
}

See it working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.