0

I'm writing a program to check a number and I have a problem; This program should print the 2nd big number of the input. The code is:

printf("Please enter number\n");
unsigned long long N;
scanf("%llu", &N);
int d1 = N % 10, d2 = -1;
while (N != 0) {
    if (N % 10 > d1) {
        d2 = d1;
        d1 = N % 10;
    }
    if (N % 10 < d1 && N % 10 > d2)
        d2 = N % 10;
    N /= 10;
}
if (d2 != -1)
    printf("2nd big digit is %d\n", d2);
else
    printf("There's no 2nd big digit!\n");

When getting an input of 123 I should get d2 = 2 in the end but this if: if (N % 10 < d1 && N % 10 > d2) is not working, but when using this code:

printf("Please enter number\n");
unsigned long long N;
scanf("%llu", &N);
int d1 = N % 10, d2 = -1, s;
while (N != 0) {
    if (N % 10 > d1) {
        d2 = d1;
        d1 = N % 10;
    }
    s = N % 10;
    if (s < d1 && s > d2)
        d2 = N % 10;
    N /= 10;
}
if (d2 != -1)
    printf("2nd big digit is %d\n", d2);
else
    printf("There's no 2nd big digit!\n");

It's working as intended, but s is N % 10 so I don't understand why the second if is working and the first one isn't, if you can explain I would really appreciate that. Sorry for my bad English :(

Barmar
  • 669,327
  • 51
  • 454
  • 560
Nati
  • 11
  • 1
  • 1
    When you compare an unsigned number with a signed number, the signed number is first converted to unsigned. So `d2 = -1` becomes the highest possible `unsigned long long`, and `N % 10` will never be larger. – Barmar Mar 04 '22 at 12:52
  • 1
    It will work if you change `N % 10 > d2` to `(int)(N % 10) > d2` – Barmar Mar 04 '22 at 12:54
  • The phrase "is not working" is generally not a good description of an error. A better description would be, for example: "When I run the program line by line in a [debugger](https://stackoverflow.com/q/25385173/12149471), the `if` branch is not taken, although I expected it to be taken, because [...]" would be a better description. – Andreas Wenzel Mar 04 '22 at 13:05
  • Also, it is generally better to provide a [mre] of the problem. Such an example could consist of a very small program which mainly contains this `if` statement and declarations which declare and initialize all variables of this `if` statement, and a `printf` statement to indicate whether the branch was taken or not. – Andreas Wenzel Mar 04 '22 at 13:09

0 Answers0