Inputting float into a program that only deals with ints

后端 未结 3 1911
星月不相逢
星月不相逢 2020-12-07 02:44

I have a program, but when I input float numbers whenever the program asks for inputs, the program abruptly skips a step and moves onto the end output. The program is below:

3条回答
  •  春和景丽
    2020-12-07 03:32

    If the next character that is to be read cannot be converted under the current format as specified by the Format Specifier, scanf stops scanning and storing the current field and it moves to the next input field (if any).

    And that particular character is treated as unread and used as the first character of next input field or any subsequent read operation.

    In the example given above, it is scanning 3 and then cannot resolve . to the format specifier "%d". Hence it stores 3 in variable a leaving .9 as unread. The control when passes to the next scanf statement, it scans ., but again as it cannot resolve . to format specifier "%d", it skips the input scanning for that field.

    Now as variable b was not assigned, it contains some garbage value. And any arithmetic operation with garbage values result into garbage values.

提交回复
热议问题