【问题标题】:printf printing zero when printing a double [duplicate]printf 打印双精度时打印零 [重复]
【发布时间】:2018-08-29 20:45:18
【问题描述】:

我有一段 C 代码,用于计算周长。 无论我在要求时为变量 Z 输入什么,它总是打印 0.000000

有什么想法吗?

#include <stdio.h>
int main()
{
    double pi = 3.1415926;
    double z = 0.0;
    printf("What is the radius of the circle? \n ");
    scanf("%1f", &z);
    double c =  2.0 * pi * z;
    printf("The circumference is %1f", c);
    return 0;
}

【问题讨论】:

  • scanf 返回什么值?另外你为什么要%1f而不是%f
  • 谢谢大家,很难区分l和1

标签: c printf


【解决方案1】:

%1f 更改为%lf

像这样:

#include <stdio.h>
int main()
{
    double pi = 3.1415926;
    double z = 0.0;
    printf("What is the radius of the circle? \n ");
    scanf("%lf", &z);
    double c =  2.0 * pi * z;
    printf("The circumference is %lf", c);
    return 0;
}

【讨论】:

    【解决方案2】:

    要读入z,一个double,你必须使用scanf("%lf", &amp;z)而不是"%1f"

    【讨论】:

      【解决方案3】:

      你们很亲密。试试这个

      #include <stdio.h>
      int main()
      {
          double pi = 3.1415926;
          double z = 0.0;
          printf("What is the radius of the circle? \n ");
          scanf("%1f", &z);
          double c =  2.0 * pi * z;
          printf("The circumference is %.1f", c);
          return 0;
      } 
      

      您的逻辑是告诉浮点它需要一个整数,但之后不需要小数

      【讨论】:

      • %f 说明符用于floats,doubles 需要%lf 说明符(带有小写 L)。您的答案中提供的代码不会产生“正确”的答案,并且可能会调用未定义的行为。 Try it online
      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多