简体   繁体   English

为什么该程序无法打印所需的输出?

[英]Why this program does not print the desired output?

I just know about the %i format specifier from this link 我只是从此链接了解%i格式说明符

Difference between format specifiers %i and %d in printf printf中格式说明符%i和%d之间的差异

and I tried to implement it with this program. 我试图用这个程序来实现它。

#include <stdio.h>

int main(){

    long long a,b;

    printf("Input: ");

    scanf("%i %lld",&b,&a);

    printf("Output: %i %lld",b,a);
}

%i worked properly but %lld stores a garbage value in variable a. %i正常工作,但%lld将垃圾值存储在变量a中。

This is the output of this program. 这是该程序的输出。

Input : 033 033 输入:033033

Output : 27 141733920846 输出:27 141733920846

Process returned 0 (0x0) execution time : 4.443 s Press any key to continue. 进程返回0(0x0)执行时间:4.443 s按任意键继续。

Can anyone explain, why I am getting the garbage value in variable a? 谁能解释,为什么我在变量a中得到垃圾值?

scanf %i takes an int * , but you're passing &b , which is a long long int * . scanf %i需要一个int * ,但是您要传递&b ,这是一个long long int * This has undefined behavior. 这具有未定义的行为。

You should be using %lli . 您应该使用%lli

The same problem occurs in printf : Use %lli to print b , not %i . printf会发生相同的问题:使用%lli打印b而不是%i

You should also check scanf 's return value to make sure two values were successfully read. 您还应该检查scanf的返回值,以确保成功读取了两个值。

First of all, using %i for a long long int is undefined behavior, so use %lli instead. 首先,将%i用作long long int是未定义的行为,因此请改用%lli

The same issue persists in the printf statement, too. 同样的问题也存在于printf语句中。

Fixed code: 固定代码:

#include <stdio.h>


int main(){

    long long a,b;
    int retval;


    printf("Input: \n");

    retval = scanf("%lli %lld",&b,&a);

    printf("Output: %lli %lld",b,a);
    printf("\nRetval: %d",retval);
    return 1;
}

Input: 输入:

033 033 033 033

Output: 输出:

Input: Output: 27 33 Retval: 2 输入:输出:27 33刷新:2

Live Demo 现场演示

Note: Always check the return value of scanf. 注意:始终检查scanf的返回值。 It returns the number of scanned items, which you should test against your expectations. 它返回已扫描项目的数量,您应该根据自己的期望进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM