how do I resolve this exercise in c/c++

Asked

Viewed 97 times

-1

at the end I still need to print which stores are presenting a price within the media, someone help me;

#include<bits/stdc++.h>
struct difsites{
    double preco;
    char loja[50];
    char site[50];
};
int main(){
    int i,j;
    double soma, media;
    struct difsites MP;
    for(i=0;i<6;i++){
        printf("Insira o nome da loja: ");
        scanf(" %50[^\n]s", &MP.loja);
        printf("Insira a URL: ");
        scanf(" %50[^\n]s", &MP.site);
        printf("Insira o valor do computador: ");
        scanf(" %lf", &MP.preco);
        soma+=MP.preco;
        media=soma/6.0;
    }
    printf("Preco medio: R$%.2lf\n",media);
}
  • 2

    If you select the code and press ctrl+k, it will be formatted cute as it is now. This makes it easier to read

  • To solve this problem, better start storing several "difsites" to be able to access them later. You will only read them once, you can only average after reading all of them and, at the end, you need to compare each "difsites" with the average. This is a good indication that you need to store them for later access

  • Why the c++ tag? You are not using anything in the c program++.

1 answer

3


First error in your code is in the variable "sum", we should initialize it as 0 if we increment from it, because of the memory junk.

double soma = 0, media;

For you to store the stores, I recommend creating a vector of structures. Getting like this

struct difsites MP[6];

The second error is time to calculate the average, you will only calculate the average when the cycle is finished.

 for(i=0;i<6;i++){  //Le cada loja do vetor, começando da posicao 0 até 5
        printf("Insira o nome da loja: ");
        scanf(" %50[^\n]s", &MP[i].loja);
        printf("Insira a URL: ");
        scanf(" %50[^\n]s", &MP[i].site);
        printf("Insira o valor do computador: ");
        scanf(" %lf", &MP[i].preco);

        soma = soma + MP[i].preco; //Soma todos os preços das lojas
    }

    media = soma/6.0;

Then to check if the store is within the average is just to make a cycle is again with a condition if less than average, display the price.

printf("Media do preco = %lf\n",media);
    for(i=0; i <6; i++){
        if(MP[i].preco <= media){
            printf("Loja %s | Preco =  R$%.2lf\n",MP[i].loja,MP[i].preco);
        }
    }
  • 1

    I guess from everything the original code bothered me, you just didn’t get the magic number. So congratulations, I’m very boring and you’ve catered to all my troubles =D

  • 1

    Kkkkkkk was worth man, I ended up not taking the magic number to try to make the code more like the original.

Browser other questions tagged

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