简体   繁体   中英

scanf in do-while loop

I was wondering why does my scanf keep going when I just ask for two parameters?

do {
    scanf("%f %f\n", &a,&b);
    printf("a=%f; b=%f;\n",a,b);
    printf("f(a)=%f; f(b)=%f; f(a)*f(b)=%f;\n",f(a),f(b),f(a)*f(b));
}
while(a>=b || f(a)*f(b)>=0);

1
2
3
a=1.000000; b=2.000000;
f(a)=-3.281718; f(b)=-0.610944; f(a)*f(b)=2.004947;
1 5
a=3.000000; b=1.000000;
f(a)=10.085535; f(b)=-3.281718; f(a)*f(b)=-33.097884;

Thank you in advance

scanf("%f %f \n ", &a,&b);

The \\n at the end makes the scanf ignore the first newline character which would have otherwise terminated input.

This will work fine :

  scanf("%f %f ", &a,&b);

remove \\n from scanf. scanf("%f %f", &a,&b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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