gpt4 book ai didi

c - 将 double 分配给 C 中的 int 变量的非直观结果

转载 作者:太空狗 更新时间:2023-10-29 16:19:13 26 4
gpt4 key购买 nike

谁能给我解释一下为什么我得到两个不同的数字,分别。 14 和 15,作为以下代码的输出?

#include <stdio.h>  

int main()
{
double Vmax = 2.9;
double Vmin = 1.4;
double step = 0.1;

double a =(Vmax-Vmin)/step;
int b = (Vmax-Vmin)/step;
int c = a;

printf("%d %d",b,c); // 14 15, why?
return 0;
}

我希望在这两种情况下都能得到 15 分,但似乎我缺少该语言的一些基础知识。

我不确定它是否相关,但我在 CodeBlocks 中进行了测试。但是,如果我在某些在线编译器 ( this one for example ) 中键入相同的代码行,我会得到两个打印变量的答案 15。

最佳答案

... why I get two different numbers ...

除了常见的 float 问题外,b 的计算路径和 c以不同的方式到达。 c通过首先将值保存为 double a 来计算.

double a =(Vmax-Vmin)/step;
int b = (Vmax-Vmin)/step;
int c = a;

C 允许使用更广泛的类型计算中间 float 学。检查 FLT_EVAL_METHOD 的值来自 <float.h> .

Except for assignment and cast (which remove all extra range and precision), ...

-1 indeterminable;

0 evaluate all operations and constants just to the range and precision of the type;

1 evaluate operations and constants of type float and double to the range and precision of the double type, evaluate long double operations and constants to the range and precision of the long double type;

2 evaluate all operations and constants to the range and precision of the long double type.

C11dr §5.2.4.2.2 9

OP reported 2

通过将商保存在 double a = (Vmax-Vmin)/step; 中, 精度被强制为 doubleint b = (Vmax-Vmin)/step;可以计算为 long double .

这个细微的差别来自 (Vmax-Vmin)/step (可能计算为 long double )被保存为 double与保留一个 long double .一个为 15(或略高于 15),另一个略低于 15。int截断将这种差异放大到 15 和 14。

在另一个编译器上,由于 FLT_EVAL_METHOD < 2,结果可能相同或其他浮点特性。


转换为 int对于接近整数的数字, float 是严重的。往往更好round()lround() .最佳解决方案视情况而定。

关于c - 将 double 分配给 C 中的 int 变量的非直观结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49012793/

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