简体   繁体   English

四舍五入浮点程序

[英]Rounding floating point program

I'm trying to write a C program to find the smallest positive integer x so that (1/x) * x is not equal to 1, using single precision. 我正在尝试编写一个C程序以使用单精度查找最小的正整数x,以使(1 / x)* x不等于1。 And I do it again with double precision. 然后我再次以双精度进行。 I know that the x for single precision is 41, however when I test it by writing C code, I still get 1.00000 我知道单精度的x是41,但是当我通过编写C代码进行测试时,我仍然得到1.00000

This is my test code 这是我的测试代码

int main()
{
    float x = 41;
    float div = 1/x;
    float test = div * x;

    printf("%f\n", test);
}

I get 1.0000 instead of a 0.999999 我得到1.0000而不是0.999999

You are not seeing the problem using 您没有看到使用的问题

printf("%f\n", test);

since the default precision used by printf for floating point numbers is 6 . 因为printf用于浮点数的默认精度是6 If you increase the precision to 10 , you will see that the number is not 1.0 . 如果将精度提高到10 ,则会看到该数字不是1.0

printf("%.10f\n", test);

prints 0.9999999404 for me. 为我打印0.9999999404

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM