为什么你不能用 C 写 scanf("%.2lf", &a) ? [英] Why you mustn't write scanf("%.2lf", &a) in C?

查看:42
本文介绍了为什么你不能用 C 写 scanf("%.2lf", &a) ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友刚刚开始学习编程.他向我展示了他的代码并问为什么它返回一些奇怪的数字.看了一下,发现他是用scanf("%.2lf", &a)来取输入的,按照习惯,我试着改成正常.然后他问我为什么它有一些奇怪的输出.谷歌搜索后,我仍然没有找到答案.

My friend have just started learning programming. He showed me his code and asked why it return some weird number. After taking a look at it, I saw that he was using scanf("%.2lf", &a) to take input, and by habit, I try to change it to normal. Then he asked me why it has some strange output. After googling around I still haven't find the answer.

谁能告诉我为什么它不起作用?

Can anybody tell me why it doesn't work?

在此先感谢您,对于冗长无关的故事以及我的英语不好,我们深表歉意.

Thank you in advance and sorry for the long irrelevant story as well as my bad English.

在下面添加代码

    int main()
    {
        double a,b,c,delta;
        printf("Nhap vao 3 so thuc a,b,c: \n");
        scanf("%.2lf %.2lf %.2lf",&a,&b,&c);
        if(a == 0 && b == 0 && c == 0) printf("Phuong trinh co vo so nghiem");
        else if(a == 0 && b == 0 && c != 0) printf("Phuong trinh vo nghiem");
        else if(a == 0 && b != 0) printf("Phuong trinh co 1 nghiem la: %.2lf",-c/b);
        else if(a != 0)
        {
            delta=b*b-4*a*c;
            if(delta<0) printf("Phuong trinh vo nghiem");
            else if(delta == 0) printf("Phuong trinh co nghiem kep: %.2lf",-b/(2*a));
            else if(delta > 0) printf("Phuong trinh co 2 nghiem la:%.2lf, %.2lf",-(b-sqrt(delta))/(4*a),-(b+sqrt(delta))/(4*a));
        }
        return 0;
    }

推荐答案

C 标准指定 scanf 转换说明符以 % 开头,POSIX 标准指定它们开始使用 %%n$.

The C standard specifies that scanf conversion specifiers begin with %, and the POSIX standard specifies they begin with either % or %n$.

C 标准和 POSIX 标准都不允许在转换说明符中使用 .,因此该字符无效.

Neither the C standard nor the POSIX standard allows for a . in the conversion specifier, so this character is invalid.

在类型说明符之前的转换说明符中可能有一个十进制整数,但它指定了类型的最大字段宽度.这意味着 scanf 将在传递 %2lf 时在停止前最多读取 2 个字符.

You may have a decimal integer in your conversion specifier before the type specifier, but it specifies the maximum field width of the type. This means that scanf will read at most 2 characters before stopping when passed %2lf.

另外,lf 指定值应该是 double,所以 a 应该是 double 类型.

Additionally, lf specifies that the value should be a double, so a should be of type double.

这篇关于为什么你不能用 C 写 scanf("%.2lf", &amp;a) ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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