nick
nick

Reputation: 67

Scanf for double not working in Dev C++

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...

Upvotes: 0

Views: 5017

Answers (4)

&#181;tex
&#181;tex

Reputation: 908

You should use

scanf("%lf", &y);

Upvotes: 1

Spikatrix
Spikatrix

Reputation: 20244

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);

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

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.

Upvotes: 3

haccks
haccks

Reputation: 106012

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.

Upvotes: 2

Related Questions