相关疑难解决方法(0)

为什么scanf()需要"%lf"用于双打,当printf()只用"%f"时可以吗?

为什么在阅读时scanf()需要l" %lf" double,何时printf()可以使用" %f",无论其参数是a double还是a float

示例代码:

double d;
scanf("%lf", &d);
printf("%f", d);
Run Code Online (Sandbox Code Playgroud)

c scanf length-modifiers

174
推荐指数
4
解决办法
29万
查看次数

printf如何处理float参数与处理double参数的方式完全相同?

直到最近,我才想到:

  • printf("%f",x) 将尝试从堆栈中读取4字节的浮点值.

  • printf("%lf",x) 会尝试从堆栈中读取一个8字节的浮点值.

但是,下面的代码似乎产生了正确的输出:

float  f = 1234.5;
double d = 12345678.9;
printf("Output = %u %u\n",sizeof(f),sizeof(d)); // Output = 4 8
printf("Output = %.1f %.1f\n",f,d);             // Output = 1234.5 12345678.9
Run Code Online (Sandbox Code Playgroud)

我相信它证明printf("%f",x)从堆栈读取一个8字节的浮点值.

这是因为两个值都正确打印,但12345678.9太大而无法放入4字节变量.

现在我的问题是:当printf使用4字节float变量调用时,编译器如何知道double在将其推入堆栈并调用之前应将其转换为8字节值printf

在调用带浮点参数的函数时,这是标准的一部分吗?

谢谢

c floating-point printf

1
推荐指数
1
解决办法
196
查看次数

标签 统计

c ×2

floating-point ×1

length-modifiers ×1

printf ×1

scanf ×1