【问题标题】:Having issues with C using float and printf [duplicate]使用 float 和 printf 遇到 C 问题 [重复]
【发布时间】:2016-07-15 00:58:14
【问题描述】:

我正在尝试在 C 中运行一些基本代码来声明 2 个浮点变量,然后将它们相除并将该值放入第三个变量中。在此之后,我打印所有 3 个。

#include <stdio.h>
int main ()
{
  /* variable definition: */
  float a, b, c; 
  /* variable initialization */
  a = 1.2;
  b = 2.7;  
  c = a / b;
  printf("Floats (a,b) and quotient (c) are : %d,%d,%d \n", a,b,c);  
   return 0;
}

我正在使用在线编译器“www.ideone.com”来编译和运行代码,这是我得到的结果:

Success time: 0 memory: 2156 signal:0

浮点数 (a,b) 和商 (c) 为:1073741824,1072902963,-1610612736

谁能看看我是否在代码中犯了错误?这是一门课,在我从 int 更改为 float 之前,每一步的指示都一切正常。

【问题讨论】:

标签: c io floating-point printf stdio


【解决方案1】:

%d 不是浮点数的正确转换,请改用%f

改变:

printf("Floats (a,b) and quotient (c) are : %d,%d,%d \n", a,b,c);

到:

printf("Floats (a,b) and quotient (c) are : %f,%f,%f \n", a,b,c);

你应该没事的。

【讨论】:

    【解决方案2】:

    你想打印浮点数,因此改变这个:

    printf("Floats (a,b) and quotient (c) are : %d,%d,%d \n", a,b,c);
    

    到这里:

    printf("Floats (a,b) and quotient (c) are : %f,%f,%f \n", a,b,c);
    

    更多信息,请查看ref

    【讨论】:

    • 感谢完美,我不知道我需要这样做,或者它特定于某种数据类型!
    • 现在你知道@RickHammer 了! ;)
    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2011-12-20
    • 1970-01-01
    相关资源
    最近更新 更多