Why can’t I change a variable in C by performing an arithmetic operation with it?

Asked

Viewed 63 times

0

I’m not getting the expected result:

libraries ...

int main (void){
    float c,r;
    setlocale(LC_ALL,"");
    printf("Digite o salário\n");
    scanf("%f",&c);
    printf("Digite o reajuste percentual:\n");
    scanf("%f",&r);
    r=r*0,01;
    c=(c* r)+c;
    printf("Salário reajustado: %.2f\n",c);
    return 0;
    }

The result always comes out with the first reading of the variable c, which would be the starting salary, as I do for it to be "updated" in the operation just below without having to add more variables?

As follows it works:

libraries ...

int main (void){
    float c,r,n;
    setlocale(LC_ALL,"");
    printf("Digite o salário\n");
    scanf("%f",&c);
    printf("Digite o percentual de reajuste:\n");
    scanf("%f",&r);
    n=c+r*c;
    printf("Salário reajustado: %.2f\n",n);
    return 0;
    }

But in addition to the additional variable, the user would have to add the readjustment between a real number from 0 to 1, not to mention that I’m sure I’ll need to use this in the future. How can I solve?

1 answer

2

Do not use comma to decimals, use dot.

#include <stdio.h>

int main (void){
    float c, r;
    printf("Digite o salário\n");
    scanf("%f", &c);
    printf("Digite o reajuste percentual:\n");
    scanf("%f", &r);
    r *= 0.01;
    c = c * r + c;
    printf("Salário reajustado: %.2f\n", c);
}

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

Just be careful that this code has several other problems, don’t think that just because it’s working it’s right.

  • Thanks bro, and thanks for the warning too, to reading my first book on C, and this program was requested in an exercise of the first chapter, I did the flowchart and when I went to pass the compiler had given it, could indicate me the other problems that exist in it?

  • Money cannot be represented with float, is mixing with double and a few other things that are only worth seeing when you’ve advanced further.

  • Ahh, yes, in the book itself talks about the other types that would only be seen later, for now it was only seen float and int even, in the correction ta as I showed the exercise of the second way

  • I hope not, books should not teach so informally, unless you make reservations.

  • I think the caveat was that the other types had not yet been seen, the book is "Algoritmos e Lógica de Programação em C, Uma Abordagem Didática" by Brazilian Silvio do Lago Pereira, publisher Érica.

Browser other questions tagged

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