0

it's my code

int main()
{
    int n,m;
    scanf_s("%d 시 %d 분에 알람을 맞춥니다. ",&n,&m);

    if(m<45)
    {

        m +=15;
        n--;
        if(n<0) n+=24;

        printf("%d 시 %d 분에 실제로 알람이 울리게 됩니다.",n,m);

    }

}

It's answer

int main()
{
    int a, b;
    scanf_s("%d %d", &a, &b);
    if (b < 45)
    {
        b += 60;
        a--;
        if (a < 0) a = 23;
    }
    printf("%d %d", a, b - 45);
}

The code above is a system that lets you ring 45 minutes earlier if you set an alarm.

If I compile it with my code and enter 0:35, the correct answer is 23: -858993445.

The answer below is normal output at 23:50

I think my answer is overflowing and I don't know why this is the result.

I want you to tell me why.

2
  • 2
    Why the text in the scanf format string? You must match that exactly in your input. Please make it a habit to check what scanf (etc.) returns. Commented Jan 9, 2020 at 7:03
  • 2
    -858993445 is not overflow. It is a magic number, convert it to hex to see that. 0xcccccccc tells you that you're reading an uninitialized variable. Defined undefined behavior when you use MSVC. Which tells you that error checking is important, you can't trust scanf() to always get the job done. Commented Jan 9, 2020 at 7:48

1 Answer 1

1

Your scanf_s() format string requires you to enter exactly the numbers embedded in the string. I'm sure you didn't enter this.

So scanf_s() just scanned the first number with the starting "%d" and stored it in n, but it could not read a value into m. So the latter variable kept its initial and random value which you see in the output.

Some steps to solve the issue:

  • Use printf() to output a prompt. scanf_s() can't do this.
  • Simplify the format string for scanf_s().
  • Check the return value of scanf_s() for success.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.