Doubt if Else returning 0

Asked

Viewed 78 times

1

I’m trying to do the following exercise:

10)A fruit plant is selling fruit with the following price list:

    Até 5 Kg        Acima de 5 Kg Morango R$ 2,50 por Kg  R$ 2,20 por Kg Maçã    R$ 1,80 por Kg  R$ 1,50 por Kg

If the customer buys more than 8 kg in fruit or the total purchase amount exceed R$ 25,00, you will also receive a 10% discount on this total. Write an algorithm to read the amount (in kg) of strawberries and the amount (in kg) of apples purchased and write the value to be paid by the customer.

I wrote the first part of the code but it’s returning R$0,00 when testing, what mistake I made? how can I fix?

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

main()
{
    float qmor,qmac,totalfru,valormor,valormac,valortotal;
    printf ("Quantidade de Morangos(Kg):");
    scanf ("%f",&qmor);
    printf ("Quantidade de Macas(Kg):");
    scanf ("%f",&qmac);
    totalfru=qmor+qmac;
    valortotal=valormor+valormac;
    if (qmor<=5)
    {
        valormor=2.50*qmor;       
    }
    else
    {
        valormor=2.20*qmor;
    }
    if (qmac<=5)
    {
        valormac=1.80*qmac;
    }
    else
    {
        valormac=1.50*qmac;
    }
    printf ("Valor Total: R$%.2f",valortotal);

}

2 answers

2


valortotal=valormor+valormac;

valormor and valormac is only initialized with a value below, you should then change that line valortotal=valormor+valormac; to the end.

    if (qmor<=5)
        valormor=2.50*qmor;

    else
        valormor=2.20*qmor;

    if (qmac<=5)
        valormac=1.80*qmac;

    else
        valormac=1.50*qmac;

    valortotal=valormor+valormac;

1

The Total Value must perform the operation after the variables valormore and valormac have been treated. As they start with the value 0 at the time of the account they continue with this value, since no operation was made with them.

Basically what’s going on is:

valormore and valormac starts by storing the value 0, then the total value variable receives the result value of the sum of these two variables. In the sequence the variables valormore and valormac are treated and receive different values but the total value continues with the same start value, because only received a copy of the sum of these two variables, persisting the value 0 in it.

Browser other questions tagged

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