【问题标题】:how to keep decimals in c如何在c中保留小数
【发布时间】:2013-09-29 13:51:03
【问题描述】:

我正在为家庭作业编写简单的代码。 当我用

定义它时,我从用户那里得到一个数字,即 3.4
scanf("%d",&a)

这样做只需要 3 次。我将a 定义为

int a; 

我该怎么办?

【问题讨论】:

    标签: c decimal


    【解决方案1】:

    我认为您对 c 编程很陌生。这是一个非常简单的工作。这可以这样做:-

    float a;
    // to input a data in the variable a
    scanf("%f",&a);
    //to display the stored data
    printf("%f\n",a);
    //or 
    printf("%.nf\n",a);//specify value of n
    //maximum value of n is 6 also is its default value
    //for e.g. printf("%.2f",a); will display decimal number upto two digits after the decimal place
    //you can know more about displaying data as
    %d: decimal value (int) 
    %c: character (char) 
    %s: string (const char *) 
    %u: unsigned decimal value (unsigned int) 
    %ld: long int (long) 
    %f: float value (float or double) 
    %x: decimal value in Hexadecimal format 
    %o: decimal value in octal format
    

    有关格式规范的avialabe 列表,请转到here

    【讨论】:

    • 感谢您的详尽回答。 n%.nlf 中的最大值是多少,例如。 long floatdouble?
    【解决方案2】:

    使用浮动

    float a;
    scanf("%f", &a);
    

    【讨论】:

    • 需要注意的是,这不会导致a中的3.4,只是一个近似值。
    【解决方案3】:

    %d 用于 int。 3.4不是int类型,可以用float。

    float x;
    scanf("%f", &x);
    

    有关数据类型的详细信息,您可以在这里查看:http://en.wikipedia.org/wiki/C_data_types

    还有这里:http://www.techonthenet.com/c_language/variables/index.php

    【讨论】:

      【解决方案4】:

      您应该将a 定义为

      float a;
      

      并在scanf 中将%d 替换为%f

      scanf("%f", &a);  
      

      我该怎么办?

      阅读Basics of Formatted Input/Output in C

      【讨论】:

      • 并将 a 定义为浮点数,而不是整数
      【解决方案5】:

      对于 int 变量非常简单,我们使用 %d 格式说明符,如果我们想要浮点数,我们使用 %f 格式说明符。因为根据IEEE int和float位图格式不同。

      【讨论】:

        【解决方案6】:

        你声明 int a 只能取整数值,所以你要做的就是让它浮动,用于带有小数点的数字

        浮动一个; scanf(%f,&a);

        【讨论】:

          猜你喜欢
          • 2023-03-22
          • 1970-01-01
          • 2014-09-03
          • 1970-01-01
          • 2023-03-05
          • 1970-01-01
          • 2015-01-22
          • 2010-12-20
          • 2020-09-11
          相关资源
          最近更新 更多