当float包含等式时,得到0作为结果

时间:2015-04-10 15:34:28

标签: c floating-point

我正在尝试编写一个非常简单的程序,将夸脱的水(用户输入)转换为C中的水分子。

#include <stdio.h>
#include <float.h>

int main(void)
{
    float water_quarts;
    float water_grams = (water_quarts*950.00);
    float water_molecules = (water_grams/3e-23F);


    printf("Enter an amount of water in quarts: \n");
    scanf("%f", &water_quarts );
    printf("%f quarts is %f grams of water.\n", water_quarts, water_grams );
    printf("%f grams is %f molecules of water.\n", water_grams, water_molecules );

    return 0;
}

然而,当我编译并运行它时,它给了我:

Enter an amount of water in quarts: 
15
15.000000 quarts is 0.000000 grams of water.
0.000000 grams is 0.000000 molecules of water.

我不完全确定我做错了什么。我在lubuntu 14.10上使用gcc 4.9.1,通过VirtualBox运行。

1 个答案:

答案 0 :(得分:5)

在您从用户(即water_grams之后)获取water_molecules的输入后,您需要为water_quartsscanf()分配值。

#include <stdio.h>
#include <float.h>

int main(void)
{
    float water_quarts;
    printf("Enter an amount of water in quarts: \n");
    scanf("%f", &water_quarts );

    float water_grams = (water_quarts*950.00);
    float water_molecules = (water_grams/3e-23F);

    printf("%f quarts is %f grams of water.\n", water_quarts, water_grams );
    printf("%f grams is %f molecules of water.\n", water_grams, water_molecules );

    return 0;
}

或者

float water_quarts;
float water_grams ;
float water_molecules ;


printf("Enter an amount of water in quarts: \n");
scanf("%f", &water_quarts );
water_grams  = (water_quarts*950.00);
water_molecules  = (water_grams/3e-23F);

否则,您正在为它们分配未初始化的值,这就是您获得意外输出的原因。

当你声明一个变量时,它会有一些垃圾值(除非你为它指定一些值),并且由此,当你做

float water_grams = (water_quarts*950.00);
float water_molecules = (water_grams/3e-23F);

water_quarts有一些垃圾值,因此,你只是给其他变量分配了一些垃圾。