0

This is part of a small project we're doing and I get stuck in this part when executing the original program. Changing the values to be integers seems to solve it but I need them as rational numbers. I really don't understand what I'm doing wrong.

 void main()
{
        float potencia;
        printf("\nInsira a potencia contratada (em kVA):");
        scanf_s("%f", &(potencia));
        while (potencia != 3.45 || potencia != 4.6 || potencia != 5.75 || potencia != 6.9 || potencia != 10.35 || potencia != 13.8 || potencia != 17.25 || potencia != 20.7);
        {
        printf("\nPotencia inserida nao disponivel, insira uma das seguintes: 3.45, 4.6, 5.75, 10.35, 13.8, 17.25, 20.7 ");
        scanf_s("%f", &(potencia));
        }

}
  • 1
    @KamilCuk - you're not wrong ... but the more fundamental problem is the OP confusing "OR" when they should be using "AND" ;) – FoggyDay Jan 19 '20 at 22:12
  • Note that you're doing (e.g.) `while (some_expression); { do_something; }` when you actually want: `while (some_expression) { do_something; }`. If you compile with `-Wall` and `-Wempty-body`, the compiler will flag this with a warning. – Craig Estey Jan 19 '20 at 23:47

2 Answers2

1

Change all the OR (||) to AND (&&), and also - remove the ; after the while

while (potencia != 3.45 && potencia != 4.6 && potencia != 5.75 && potencia != 6.9 && potencia != 10.35 && potencia != 13.8 && potencia != 17.25 && potencia != 20.7)
Witterquick
  • 6,048
  • 3
  • 26
  • 50
  • While it didn't work at first, after seeing @KamilCuk 's [comment that linked to this](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) both solved it, thanks! – Martinho Tavares Jan 20 '20 at 16:23
0

You have a problem with your logic. You should have used && istead of || .
Secondly, put an "f" after float values to make sure comparison works as you expect. See Comparison of a float with a value in C.

void main()
{
    float potencia;
    printf("\nInsira a potencia contratada (em kVA):");
    scanf_s("%f", &(potencia));
    while (potencia != 3.45f && potencia != 4.6f && potencia != 5.75f && potencia != 6.9f && potencia != 10.35f && potencia != 13.8f && potencia != 17.25f && potencia != 20.7f)
    {
        printf("\nPotencia inserida nao disponivel, insira uma das seguintes: 3.45, 4.6, 5.75, 10.35, 13.8, 17.25, 20.7 ");
        scanf_s("%f", &(potencia));
    }
}
t.m.
  • 1,430
  • 16
  • 29