scanf中的%d不起作用。编号4223092出现[关闭]

问题描述 投票:1回答:3

任何人都可以帮我这个代码吗?我没有看到任何问题,但不知何故它不起作用。当我输入我最喜欢的号码并按回车键时,会出现号码4223092。


int target;
int after;

#include <stdio.h>

int main() {

    printf("What is 6 x 4?: ");
    scanf("%d", &target);

    if (target == 24) {
        printf("Correct!\n");
        printf("By the way what is your favorite number?: ");
        scanf("%d", &after);
        printf("%d is my favorite number too!\n", &after);

    } else {
        printf("Wrong!\n");
        printf("By the way what is your favorite number?: ");
        scanf("%d", &after);
        printf("%d is my favorite number too!\n", &after);

    }

    return 0;
}
c printf scanf
3个回答
4
投票

在你的代码中

 printf("%d is my favorite number too!\n", &after);

你不需要&。您想要打印值,而不是地址。

只是为了让你知道,在它的当前形式,通过int *作为%d的参数调用undefined behaviour。因此,您无法以任何方式证明输出的合理性。

%d期待int类型的论证,而不是int *。传递不兼容的参数类型会调用UB。

引用C11,章节§7.21.6.1,P9

[...]如果任何参数不是相应转换规范的正确类型,则行为未定义。


1
投票

printf函数不需要将变量的地址打印到stdout。只需传递变量的名称,如下所示:

printf("%d is my favorite number too!\n", after);

%d格式说明符看起来显示整数值。如果你传递其他东西,比如你的情况下的int *,它会给你带来奇怪和意想不到的结果。

要使此答案更完整,要打印指针变量,请使用%p格式说明符。


-1
投票

值4223092是“after”变量的地址。

在C语言中,您不需要指针来打印值。您只需要变量的值。因此,无论何时打印变量,只需打印变量而不是变量的指针(地址)。

所以只需更改代码中的以下行

printf("%d is my favorite number too!\n", &after);

printf("%d is my favorite number too!\n", after);
© www.soinside.com 2019 - 2024. All rights reserved.