首页 > 解决方案 > 当我使用scanf()时,我想知道这两者有什么不同

问题描述

我不知道如何用语言来解释,所以我先给你一个问题。所以如果你之前有同样的问题,请原谅我。

#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d %d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}
#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d%d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}

我一直想知道我在编码时scanf("%d %d", &a, &b);scanf("%d%d", &a, &b);编码时的区别。所以我的问题是,这两个代码在功能上是否相同?

标签: c

解决方案


两段代码没有区别。无论哪种方式都有效,您可以使用您喜欢的任何一种。

但是,如果考虑 %c 即 char 数据类型说明符,那么事情就会变得有趣。为了理解差异,请考虑以下程序:

    int main()
    {
        char x,y; //declaring two variable of char data type
        printf("Part 1");
        scanf("%c%c",&x,&y); //no space between the specifiers
        printf("%c %c",x,y);
        printf("Part 2");
        scanf("%c %c",&x,&y); //single white space between the specifiers.
        printf("%c %c",x,y);
        return 0;
    }

程序执行时的截图 在此处输入图像描述

在第 1 部分中,变量 x 存储字符“A”,变量 y 存储“”(空白)。在这种情况下,空间被视为输入,因此忽略了实际输入。在第 2 部分中,变量 x 存储“A”而 y 存储“B”,因为明确提到输入中需要空格。

希望这可以帮助 :)


推荐阅读