用scanf()读取时,double类型的变量不起作用 [英] Variable of type double not working when read by scanf()

查看:365
本文介绍了用scanf()读取时,double类型的变量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main(){
    double d;

    scanf("%f", &d);
    printf("%f\n\n",  d);

    system("pause");
    return 0;
}

这就是我得到的:
错误

此代码用于读取变量double并将其显示在屏幕,但仅显示 0.0 ...。

This code is meant to read the variable double and display it on the screen but it does only display "0.0...".

如果我只是将变量类型更改为 float ,它将完全满足我的要求,但是如果将其设为 double 只会读取 0。为什么?

If I just change the variable type to float it does exactly what I want but if I make it a double it just reads '0'. Why?

推荐答案

在您的代码中,

 scanf("%f", &d);

是错误的。对于 scanf()%f 期望指向 float

is wrong. For scanf(), %f expects a pointer to float as argument.

引用 C11 ,第§7.21.6.2章, fscanf()

Quoting C11, chapter §7.21.6.2, fscanf()


a e f g

匹配一个可选的带符号浮点数,无穷大或NaN,其
格式与strtod $的主题序列所期望的格式相同b $ b函数。 相应的参数应该是指向浮动的指针。

Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

如果要扫描一个 double ,则必须使用

In case you want to scan a double, you have to use

 scanf("%lf", &d);






FWIW,为任何格式传递不兼容的参数类型指定者调用未定义的行为

引用 C11


[...]除非用*表示禁止分配,将转换结果
放置在第一个参数指向的对象中,该参数位于
之后的格式参数中,该参数尚未收到转换结果。 如果此对象
没有适当的类型,或者如果转换结果无法在该对象中表示为
,则该行为是不确定的。

这篇关于用scanf()读取时,double类型的变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆