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]);
}
}
And what was supposed to happen if a decimal was typed?
– Francisco
If you’re defining yourself as
int
then you can only put whole numbers, if you want with decimals then it isfloat
– Fábio Morais
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.
– anonimo