双重不在C中存储数字(数字太小)

时间:2017-11-27 05:06:21

标签: c floating-point integer

这是我的问题,我需要计算ms中有多少个时钟周期,而我的pll等待TM4C123。然而,在我的双重值上出现的值为零,使我的其他值不正确。任何帮助将不胜感激。

#include <stdio.h>

int main()
{
    float ms_cycled;
    float us_cycled;
    int ms_cycle;
    int us_cycle;
    unsigned long MHz = 50;
    double TPC = 1/(MHz*10000000); //calculate time per clock cycle

    //calculate cycles for ms
    ms_cycled = 0.001/TPC;
    ms_cycle = ms_cycled;
    //calculate cycles for us
    us_cycled = 0.000001/TPC;
    us_cycle = us_cycled;
    printf("TPC = %.16f \n", TPC);
    printf("ms_cycled = %f \n", ms_cycled);
    printf("us_cycled = %f \n", us_cycled);
    printf("ms_cycle = %i \n", ms_cycle);
    printf("us_cycle = %i \n", us_cycle);
    return 0;
}

我得到的输出是:

TPC = 0.0000000000000000                                                                                                                             
ms_cycled = inf                                                                                                                                      
us_cycled = inf                                                                                                                                      
ms_cycle = -2147483648                                                                                                                               
us_cycle = -2147483648

1 个答案:

答案 0 :(得分:1)

表达式1/(MHz*10000000)的类型为unsigned long,值为0.将结果存储在double中不会使结果为零。请改用1.0/(MHz*10000000)