gpt4 book ai didi

c - 输入一个精度为两位数的 float

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:22 24 4
gpt4 key购买 nike

我正在解决一个问题,要求我输入一个精确到 2 位精度的 float 。

我知道如何打印具有两位数精度的 float ,但如何在这种情况下输入 float ?我认为这是我的程序的问题,因为没有编译错误,但它只是说错误的答案。我正在使用 C 语言。

我尝试按照以下方式读取具有两位数精度的 intfloat:

int x;
float balance,y;
scanf("%d %.2f",&x,&y);

要获得完整的引用,这里是 question和我的 solution

最佳答案

建议的解决方案中存在问题。根据cplusplus.com ,格式 f 只接受宽度而不接受精度。

如果您控制了 scanf 的返回(您应该始终做的事情 - 现在您知道为什么了!)您会立即看到问题:

int x, cr;
float balance,y;
cr = scanf("%d %.2f",&x,&y);
if (cr != 2) {
fprintf(stderr, "Read error : cr = %d\n", cr);
}

给定任何输入,您将得到:

Read error : cr = 1

几乎没有变化的可能实现:

cr = scanf("%d %f",&x,&y);
if (cr != 2) {
fprintf(stderr, "Read error : cr = %d\n", cr);
}
// should round to only two digits - within floating point accuracy
y = (((double)((int)(y * 100 + 0.5))) / 100.);

如果你有一个系统,其中 math.h 包含 round(不是 MSVC :-( ),最后一行最好写成(感谢 chux 的提议) :

y = round(y * 100)/100

因为上面的公式对于负 y 和 y > INT_MAX/100

会失败

如果您真的需要两位小数的精确精度,正确的方法是将所有计算作为 long 上的integer,将数字乘以 100。我留给读者作为练习:-)

关于c - 输入一个精度为两位数的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27946176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com