Scanf for double not working in Dev C++

2020-05-01 06:23发布

I am having problem with floating point numbers. I think something is clashing here.

The output is :

Screenshot of the output

My code :

#include <stdio.h>


int main(){


    double y;

    printf("enter a decimal number: ");
    scanf("%f", &y);

    printf("%f\n", y);

    fflush(stdin);

    getchar();
    return 0;

    }

I am using Dev C++ 4.9.9.2 and first of all, I have to flush the carriage return out several times if it's not read previously . So if there is any alternative there then tell me. And secondly the output is giving this...

4条回答
对你真心纯属浪费
2楼-- · 2020-05-01 06:45

Use

scanf("%lf", &y);

instead. Since scanf("%f", &y); works for floats only.

If you enable compiler warnings it would tell you that the format specifier "%f" expects a float * and not double * argument.

查看更多
Rolldiameter
3楼-- · 2020-05-01 06:46

Using wrong format specifier invoke undefined behavior and that's why you are getting unexpected result. Once UB is invoked, you may either get expected or unexpected result. Nothing can be said.
Use %lf to read double type data.

查看更多
三岁会撩人
4楼-- · 2020-05-01 06:46

You should use

scanf("%lf", &y);
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-05-01 07:05

You are using the wrong format specifier in the scanf and doing this will result in UB(Undefined Behaviour).The correct format specifier for a double is %lf while that of a float is %f. So Just change your scanf to

scanf("%lf",&y);
查看更多
登录 后发表回答