【问题标题】:scanf() not giving correct values for entered doublesscanf() 没有为输入的双打给出正确的值
【发布时间】:2013-10-25 16:05:02
【问题描述】:
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 的低值和高值。我在程序开始时初始化了它们,现在我正在尝试为它们输入值。

我做错了什么?

{附注我在 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

【问题讨论】:

  • 强烈建议检查scanf()结果:if (2 != scanf("%lf%lf", &low, &high)) handle_error();
  • \nprintfs 的末尾。 (或fflush(stdout);)。
  • 注意:printf("%lf%lf",low,high) 中的l 是可选的。带/不带l 的结果相同。 scanf() 并非如此。
  • lf和f有什么区别?
  • 我得到“函数'handle_error'的隐式声明...”(程序不运行)

标签: c input double scanf lf


【解决方案1】:

对于doubles 和scanf,您需要%lf,如果您有两个doubles 要阅读,您还需要其中两个。

所以改变:

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

【讨论】:

    【解决方案2】:

    试试这个,

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

    【讨论】:

    • 仍然没有像我输入的值那样输出低和高。
    • 你能告诉我你输入的低值和高值吗?
    • 我输入了 1 和 2。(见上面的编辑)当我检查错误时发生了一些新的事情。
    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多