0

This is my code:

#include<stdio.h>
#include<math.h>
int fruitloops(int n)
{
    if(n%2==0)
        {
            printf("The number is even.\n");    
        }
        else
        {
            printf("The number is odd.\n");
        }
}



int main()
{
    int n;
    printf("Enter any number you want to check the parity of: \n");
    scanf("%d",&n);
    if(n==floor(n))
    {
        fruitloops(n);
    }
    else if(n!=floor(n))
    {
        for(int i=0;i<10;i++)
        {
            printf("Enter an integer, not any random number: \n");
            scanf("%d",&n);
            if(n=floor(n))
            {
                fruitloops(n);
                break;
            }
            else
            {
                continue;
            }
            i++;
        }
    }
    return 0;
}

It takes in my input but doesn't give me a correct answer and i can't seem to find out where i went wrong for example when i put in 10.5 i get even as the output but it seems to work fine when i use an integer

  • 2
    You’re using `scanf()` with `%d`, so it reads digits until it comes to the decimal point, then it stops. You can confirm this by printing the result you get. There’s no way for it to store 10.5 in an `int`. – Tom Zych Mar 16 '20 at 18:40
  • 2
    `n` is an `int`, 10.5 is a float, the `%d` format specifier for `scanf` is looking for an `int`. If you want to input a mix of floats and ints, you'll need to accept the input as a string and do more complicated parsing. – yano Mar 16 '20 at 18:40
  • 1
    The proposed duplicate does not address the specific issues of this code snippet, I think... – Ctx Mar 16 '20 at 18:44
  • Oh sorry, I noticed my mistake but what should i do to rectify it, i tried to change it to float values but it gave an error while doing n%2 in the function, could someone please help out – Learning... Mar 16 '20 at 19:06
  • what do you want to do? Round the number to nearest whole number then determine if it's even or odd? Or you just want to drop whatever decimal part might be there? – yano Mar 16 '20 at 19:45
  • i want to make the user input another value in case the input is anything other than an integer, eg. a string or a number with the decimal part – Learning... Mar 16 '20 at 19:58
  • @TomZych could you please help me out – Learning... Mar 17 '20 at 11:29
  • @yano could you help me out – Learning... Mar 17 '20 at 11:29
  • Then you can probably just check the return value of [`scanf`](https://linux.die.net/man/3/scanf). It returns the number of items successfully matched, so `%d` is looking for integers, if the user types anything other than an integer, it won't match, and the return value will be one less than expected. You could put that check in a do-while loop until the user enters an integer. I think what I've said is right, but there may be some complicating details, I'm not very familiar with `scanf`. – yano Mar 17 '20 at 15:09

0 Answers0