c中的数字小数

时间:2013-09-29 14:34:44

标签: c decimal printf scanf

我刚问了一个问题,却无法得到我想要的东西,而且由于时间过长而无法编辑和回复。我的问题是相同的,它是该问题的链接。how to keep decimals in c

#include<stdio.h>

int main()
{
    float b,c,;
    int a,kk;
    printf("Welcome to the unit conversion program\n");
    printf("This program can convert the measurements of;\n");
    printf("1-Length\n");
    printf("2-Mass\n");
    printf("Please select the number that corresponds to the measurement you want to convert in:\n");
    scanf("%d",&a);
    if (a==1){
          printf("Your number will be converted from inches to centimeters.\n");
          printf("Please enter the length.\n");
          scanf("%f",&b);
          c=b*2.54;
          printf("%f inch is %f cm.",b,c);
          scanf("%d",kk); \. to avoid to shut the cmd windows .\
          }

      else if (a==2){
           printf("Your number will be converted from pounds (lbs) to kilograms");
           printf("Please enter the mass.\n");
           scanf("%d",&b);
           c=b*0.45359237;
           printf("%d lbs is %d kgs.",b,c);
       }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

变化:

scanf("%d",&b);

printf("%d lbs is %d kgs.",b,c);

为:

scanf("%f",&b);

printf("%f lbs is %f kgs.",b,c);

您将 b 声明为float,将输入视为小数&amp;以后打印浮点数b,c为十进制?请研究一本书Deital & Deital for C/C++是一本神奇的书。

答案 1 :(得分:0)

错误是%dscanf的格式说明符中的printf代表十进制,因此它需要一个int(在scanf的情况,指向int

的指针

由于您将bc声明为float,行中的%d

scanf("%d",&b);

printf("%d lbs is %d kgs.",b,c);

应分别更改为%f

一点建议:使用double代替float。它提供更高的精度,其性能在许多机器中更好。缺点是它占用的空间比float多,但在大多数情况下这不是问题。

如果您使用%f,则应printf %lfscanf使用double