c - 将打印浮点值转换为分数的程序不起作用..?

标签 c math floating-point decimal

所以我试图编写一个程序,它采用浮点值并用分数表示它。我面临一个奇怪的问题。这是我的程序:

#include<stdio.h>
#include<math.h>
int gcd(int,int);

void main()
{
    int n,n1,n2,g;
    float a,a1;
    printf("Enter number of digits after decimal point: ");
    scanf("%d",&n);
    printf("Enter number: ");
    scanf("%f",&a);
    n2=pow(10,n);
    a1=a*n2;
    n1=(int)a1;
    g=gcd(n1,n2);
    n1/=g;n2/=g;
    printf("The number is %d/%d",n1,n2);
}


int gcd(int a,int b)
{
    int x,flag=0;
    int n1=((a>b)?a:b);
    int n2=((a<b)?a:b);
    for(x=n1;x>=1;x--)
    {
        if(n1%x==0 && n2%x==0)
        {
            flag=1;break;
        }
    }
    if(flag==1)
        return x;
    else
        return 1;

}

现在这个程序给出了只有 1 位小数的数字的正确答案。例如:

Enter number of digits after decimal point: 1
Enter number: 2.5
The number is 5/2

但是,对于小数点后两位或更多位的数字,它会给出错误的答案。例如:

Enter number of digits after decimal point: 2
Enter number: 2.50
The number is 247/99

我知道 float 不准确,但我没想到会有这么大的变化。有什么办法可以解决这个问题并使这个程序正常工作吗???

最佳答案

对我有用。我相信原因是您使用 pow(10, n) 并且 powinexact on your platform 。使用简单的 for 循环代替:

n2 = 1;
for (int c = 0; c < n; c++) {
    n2 *= 10;
}

关于c - 将打印浮点值转换为分数的程序不起作用..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43817480/

相关文章:

c++ - 凸包算法 - 格雷厄姆扫描最快的比较函数?

分组算法使总和接近目标值

c - 为什么打印 unsigned char 会输出这么大的数字?

c - 使用变量 C 编程时第二个 printf 不起作用

c++ - 如何在顶部 2D 小 map 上显示以 3D 视角呈现的平面世界的可见部分?

C++:奇怪的 float 学结果

java - 归一化双 vector 不是单位长度到机器精度

c - 我试图编写一个程序,看起来完全没问题,但我找不到它不起作用的原因,任何帮助将不胜感激

c - 对指向指针的指针使用 realloc() 时,指针值会发生变化

python - 是什么导致 Python 的 float_repr_style 使用 legacy?