使用 scanf 函数为变量赋值

Assigning a value to a variable with the scanf function

无论我为 x 输入什么值,y 值的输出始终为 1。知道为什么吗?

#include <stdio.h>    
int main() {
    int x, y;
    y = scanf("%d", &x);
    printf("y = %d\n", y);
    return 0;
}

来自scanf(3) - Linux man page

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

因为scanf return值是写入的项目数(在你的例子中,1,因为只扫描了1个int),而不是扫描字符的整数值

int main() {
    int x, y, z, n;
    n = scanf("%d", &x);
    printf("n = %d\n", n);                 // prints 1
    n = scanf("%d%d", &x, &y);
    printf("n = %d\n", n);                 // prints 2
    n = scanf("%d%d%d", &x, &y,&z);
    printf("n = %d\n", n);                 // prints 3
    return 0;
}