Read only whole numbers in c

Asked

Viewed 1,139 times

1

I’m new to programming and I’m having a problem, I made a code that reads three whole numbers.

#include <stdio.h>
#include <stdlib.h>
int main () {
int i,v[3];
for (i = 0; i < 3; i++)
{
        printf("Numero:");
        scanf("%d",&v[i]);
}
for (i = 0;  i < 3; i++)
{
    printf("%d\n",v[i]);
}
}

However, when a decimal number is entered, it does not work as it should. For example, I put 2.5 as input and the program just let me do it and generated it below:

 Numero:2.5
 Numero:Numero:2 
 0
 1

I also made another code to see if it worked but still the same problem

#include <stdio.h>
#include <stdlib.h>
int main() {
int k = 0,i,v[3],valor;
for (i = 0; i < 3; i++)
{
   do
    {   
        printf("Numero:");
        scanf("%d",&v[i]);
        valor = v[i] - int(v[i]);
        if (valor == 0) k = 1;
        else printf ("Digite apenas inteiros\n");
    }while(k != 1);
}
for (i = 0;  i < 3; i++)
{
    printf("%d\n",v[i]);
}

}

  • 1

    And what was supposed to happen if a decimal was typed?

  • 2

    If you’re defining yourself as int then you can only put whole numbers, if you want with decimals then it is float

  • The entries provided must be compatible with what is specified in the reading instruction. If your input can be anything and you want to select parts of it then read as a string of characters and then do the proper handling of the read string.

1 answer

2

Swap int for float, int is for integers (1/2/3), float represents fractional numbers and real numbers (this includes integers).

#include <stdio.h>
#include <stdlib.h>
int main () {
float v[3];
int i;
for (i = 0; i < 3; i++)
{
    printf("Numero:");
    scanf("%f",&v[i]);
}
for (i = 0;  i < 3; i++)
{
    printf("%.1f\n",v[i]);
    //coloca o print apenas com 1 casa decimal, editar conforme o pedido do projeto.
}
return 0;
}

Refilled here and worked perfectly.

Browser other questions tagged

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