scanf()没有为输入的双精度值给出正确的值

时间:2013-10-25 16:05:02

标签: c input double scanf lf

double low = 0 , high = 0.0,n = 0.0;
----
printf("Enter the integral limits (low high): ");
scanf("%lf %lf", &low, &high);

printf("%lf%lf",low,high);
printf("Enter the number of subinternals (n): ");
scanf("%lf",&n);

当我测试这个程序时(通过

    printf("%lf%lf",low,high);) (6th line)

对于低和高,我得到0.000000和0.000000的值。我在程序开始时初始化它们,现在我正在尝试为它们输入值。

我做错了什么?

{P.S。我在Windows 7笔记本电脑上。我已经尝试将“%f”更改为“%lf”并返回“%f”)

我该怎么办? (请帮忙!)

编辑: 我不确定刚刚发生了什么。 我用

检查了错误
        if (2 != scanf("%lf %lf", &low, &high))
               printf("scanf failed!\n")

而发生的事情是在我的“......(低高)之后:” 我输入了1和2,然后程序正在等待更多输入,然后我再次输入1和2,这一次,它给了正确的打印...不确定发生了什么?

输出屏幕: http://s1288.photobucket.com/user/Kdragonflys/media/ss_zps6b85396e.png.html

2 个答案:

答案 0 :(得分:2)

对于%lf double,您需要scanf,如果您有两个double可供阅读,则还需要其中两个。

所以改变:

scanf("%f", &low, &high);

为:

scanf("%lf %lf", &low, &high);

同样改变:

scanf("%f",&n);

为:

scanf("%lf",&n);

注意:错误检查总是一个好主意 - scanf返回成功处理的值的数量。因此,您可以检查第一个scanf调用是否正常运行:

if (scanf("%lf %lf", &low, &high) != 2)
    printf("scanf failed!\n");

答案 1 :(得分:0)

试试这个,

double low = 0.0 , high = 0.0,n = 0.0;
----
printf("Enter the integral limits (low high): ");
scanf("%lf %lf", &low, &high);

printf("%lf %lf",low,high);
printf("Enter the number of subinternals (n): ");
scanf("%lf",&n);