Simple declaration of a variable for scanf

1

I already know how to declare a variable in the traditional way using scanf() , but I'm thinking in a way that I can use fewer rows and make the code more organized (this is what I tried with the variable valor ). / p>

It turns out that when I run the program the value 1 is always printed on the screen. Why is the value 1 printed on the screen?

Is there a more organized way to use scanf() without using another line (similar to what I'm trying to do)?

Code no replit - >

#include<stdio.h>

int main()

{
  int resultado = 1;
  printf("Coloque um valor: ");
  int valor = scanf("%d", &valor);

while (valor > 0){
  resultado = resultado * valor;
  valor =  valor - 1;}


  printf("O exponencial é: %d\n", resultado);


}
    
asked by anonymous 15.09.2017 / 02:58

2 answers

1

There is not much to do. I will demonstrate to the most organized and with less lines, in addition to fewer characters.

Note that scanf() does not declares variable .

Actually scanf() should not be used like this . We use exercise. This function returns a success information and not the one entered. What was typed is always placed in the variable used as the function argument. That's why you need to pass it on as a reference.

Before using any function, read the documentation and understand all aspects of it. scanf() documentation.

Do not try to reduce the number of rows at any cost, just lower those that get more organized as well.

#include<stdio.h>

int main() {
    printf("Coloque um valor: ");
    int valor;
    scanf("%d", &valor);
    int resultado = 1;
    while (valor > 0) {
        resultado *= valor;
        valor--;
    }
    printf("O exponencial é: %d\n", resultado);
}

See running on ideone . And at Coding Ground . Also put it in GitHub for future reference .

An alternative with for :

#include<stdio.h>

int main() {
    printf("Coloque um valor: ");
    int valor;
    scanf("%d", &valor);
    int resultado = 1;
    for (; valor > 0; valor--) resultado *= valor;
    printf("O exponencial é: %d\n", resultado);
}
    
15.09.2017 / 03:11
0

I believe the while loop is not starting once you declared the value variable the wrong way. So, as you declared the value of the result variable, right at the beginning of the program, saving the value 1 that information will be passed to the last printf of the program.

There is no need to assimilate user input into the scanf function with the "=" symbol as this is the "& which precedes the value variable.

    
15.09.2017 / 03:11