如何用c语言计算小数点后位数

#include "stdio.h"
#include "conio.h"
void main() /*计算小数后位数*/
{
float number=100.25432;
int temp;
int dot_loc=0;
temp=(int)number;
while(number-temp>0)
{
number=number*10;
temp=(int)number;
dot_loc++;
printf("%f\n",number-temp);
getch();
}
printf("digits after decimal point: %d\n",dot_loc);
getch();
}
float表示的小数不准确,怎样才能解决这个问题。难道这个问题无解?

这个要看小数按什么格式输入。

如果按%s输入,也就是按字符串格式输入,先找到小数点的位置,然后统计下小数点后数字的长度。

具体实现可参考:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char a[128];
    while(scanf("%s",a)!=EOF)
    {
        if(strstr(a,".")!=NULL)
        printf("%d\n",strlen(strstr(a,".")+1));
        else 
        printf("0\n");
    }
    system("pause");
    return 0; 
}

如果按%f(对应float类型小数)或者%lf(double类型的小数)方式读入,则需要先去掉整数部分,然后看小数部分一直乘10减去整数部分,知道等于0,统计,乘了几次10,但是由于浮点数在计算机中存的并不是准确值,这个往往得不到正确的结果。可以使用sprintf(str,"%g",f);,然后由于f毕竟不是准确值,还是会出现有些问题,源码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char a[128];
    float f;
    while(scanf("%f",&f)!=EOF)
    {
        sprintf(a,"%g",f);
        if(strstr(a,".")!=NULL)
        printf("%d\n",strlen(strstr(a,".")+1));
        else 
        printf("0\n");
    }
    system("pause");
    return 0; 
}

这是最后一个已经出现错误,所以遇到要精确判断小数点的位数,最好直接按字符串读入,这和图灵机的工作原理暗暗相合。

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-09-25

先变成字符串,然后再求(纯手打未测试)

#include <stdio.h>
#include <string.h>
void main()  {
    char * ptr;
    char strFloat[20];
    float number=100.25432;
    sprintf(strFloat, "%f", number);
    ptr = strstr(strFloat, ".");
    if (ptr != NULL) {
        printf("digits after decimal point: %d\n", strlen(ptr) - 1);
    }
}

本回答被提问者采纳
第2个回答  2013-09-16

将 float 类型变为 double 类型,你试试吧:

    double number=100.25432;
    double temp;


原来你的目的不是改你的程序,那求小数位数的方法太多了

追问

单片机里没有double,double会被强制转成float,再说double其实也不准确。对,就是求小数点后位数。

追答

你可以看到,double 类型输出和 float 类型输出的对比;

我不知道你要精确到什么程度;

关于其它的方法再讨论!!

  double 类型

  float 类型

追问

他不精确,就会导致计算出的小数点后位数比实际的多,因为后面还有数。不是多精确的问题,是根本求不出来的问题。上面那个程序也是不对的,不过我已经采纳了,转化为char的时候也是不准确的。

相似回答