在c中向右移动小数位

Rob*_*ert 5 c double decimal

我是C的新手,当我运行下面的代码时,输​​出的值是12098而不是12099.

我知道使用小数总是涉及一定程度的不准确,但有没有办法准确地将小数点每次都移动到正确的两个位置?

#include <stdio.h>

int main(void)
{
    int i;
    float f = 120.99;

    i = f * 100;
    printf("%d", i);
}
Run Code Online (Sandbox Code Playgroud)

use*_*109 5

使用该round功能

float f = 120.99;
int i = round( f * 100.0 );
Run Code Online (Sandbox Code Playgroud)

但请注意,float通常只有6或7位精度,因此有一个最大值可以使用.float无法正确转换的最小值是数字131072.01.如果乘以100并舍入,结果将是13107202.

您可以使用double值扩展数字范围,但即使double范围有限也是如此.(A double具有16或17位精度.)例如,将打印以下代码10000000000000098

double d = 100000000000000.99;
uint64_t j = round( d * 100.0 );
printf( "%llu\n", j );
Run Code Online (Sandbox Code Playgroud)

这只是一个例子,找到最小的数字是超过a的精度double作为读者的练习.