0
#include <stdio.h>

int evenDigits1(int num);

int main() {
    int number;
    printf("Enter a number: \n");
    scanf("%d", &number);
    printf("EvenDigits(): %d\n", evenDigits1(number));
    return 0;
}

int evenDigits1(int num) {
    int x, result, i = 1;
    float evenNum = 0;
    while (num != 0) {
        x = num % 10;
        if (x % 2 == 0) {
            evenNum += x;
            evenNum /= 10;
            i *= 10;
        }
        num /= 10;
    }
    result = evenNum * i;
    if (result == 0) {
        return -1;
    } else {
        return result;
    }
}

Why is it when I enter 4488 or 1144889, it will display 4487 instead of 4488? For other number such as 44488 or 123456, it will show correctly (44488 and 246).

How do I display 4488 as 4488 instead of 4487?

Thanks for your help.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Barnacle Own
  • 85
  • 1
  • 9
  • It seems like a perfect time to learn how to use a *debugger* to step through your code statement by statement while monitoring variables and their values. – Some programmer dude Feb 02 '20 at 13:19
  • 2
    Why do you define `evenNum` as a floating pointer number? This is actually a big hint to your problem... – Some programmer dude Feb 02 '20 at 13:21
  • What should I define my evenNum? I define it as floating pointer because of decimal. – Barnacle Own Feb 02 '20 at 13:27
  • Why? You initialize it to an integer value. You add an integer value. You divide an integer value to get an integer value result (and here things will start to go wrong) and you multiply by an integer. – Some programmer dude Feb 02 '20 at 15:07
  • Is there anyway to fix this? Can I add .0 behind the integer value to make it a float? Or how should I proceed. Thanks for your clarification. – Barnacle Own Feb 02 '20 at 16:37
  • 1
    You don't *need* decimals here, only integers. So make `evenNum` an `int` and you won't have the rounding errors that comes with floating point arithmetic. – Some programmer dude Feb 02 '20 at 16:54
  • But I will get 0 since evenNum / 10 will be 0.4 if my evenNum is 4. – Barnacle Own Feb 03 '20 at 13:46
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/207111/discussion-between-barnacle-own-and-some-programmer-dude). – Barnacle Own Feb 03 '20 at 15:23

0 Answers0