0

hello Im still new at programming so sorry if it's a dumb question but what's the error in my program? every number I input it will always say it's an odd number and the else statement doesn't work.

cout << "This program will determine whether a number is odd or even. \n";
cout << "Please enter a number ---> ";
cin >> number;

lastDigit = number % 10;

if ( number % 10 == 1,3,5,7,9)
{
    cout << "\nThe last digit is " << lastDigit;
    cout << endl << number << " is odd.";
}

else
{
    cout << "\nThe last digit is " << lastDigit;
    cout << endl << number << " is even.";
}

getch ();   
return 0;

}`

  • Convert to a string. Get last character. Is it an even number? – tadman Mar 18 '21 at 06:35
  • 3
    Tip: `if ( number % 10 == 1,3,5,7,9)` is not doing what you think it does. – tadman Mar 18 '21 at 06:36
  • You normally check whether a number is odd by computing the remainder of division by 2 since "being odd" means "not being divisible by 2" – ForceBru Mar 18 '21 at 06:36
  • `cin`ing it as a string directly and checking the last character would seem to be the simplest solution in your case, though `% 2` is generally how you tell if something is even or odd. – mediocrevegetable1 Mar 18 '21 at 06:37
  • Related:duplicate: [How do I check if an integer is even or odd?](https://stackoverflow.com/questions/160930/) – Remy Lebeau Mar 18 '21 at 09:03

3 Answers3

2

if ( number % 10 == 1,3,5,7,9) is the problem here. Although it compiles, that's not doing what you intend.

The , syntax here does not mean "one of", it means, effectively, "but then" which is not what you want. This ends up evaluating as if (9) as the other parts are evaluated and the results discarded.

This can be done with a switch:

switch (number % 10) {
  case 1:
  case 3:
  ...
  case 9:
    // Odd!!
    break;
  default:
    // Even!
}

What you really need is just if (number % 2) as that's how "evenness" is decided. If that's true, you have an odd number, otherwise even.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

if ( number % 10 == 1,3,5,7,9) is not doing what you think it actually does. What is actually required to check whether a number is odd or even is :

//n -----> number

//l------->lastdigit of the number

    l = n % 10; 

    if(l % 2 == 0)
    {printf("%d is even:", l);}
    
    else
    {printf("%d is odd:", l); }
Karishma
  • 11
  • 2
0
lastDigit = number % 10;

if ( lastDigit % 2 == 1)
{
    cout << "\nThe last digit is " << lastDigit;
    cout << endl << number << " is odd.";
}
else
{
    cout << "\nThe last digit is " << lastDigit;
    cout << endl << number << " is even.";
}