Reading only integers in c

0

I'm new to programming and I'm having a problem, I made a code that reads three integers.

#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 you enter a decimal number, it does not work as it should. For example, I put 2.5 as input and the program just let me do that 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]);
}

}

    
asked by anonymous 09.10.2018 / 02:49

1 answer

0

Change int by float, int is for integers (1/2/3), float represents fractional numbers and real numbers (which 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;
}

Refined here and it worked perfectly.

    
09.10.2018 / 14:39