奇怪的双到int转换行为在c

奇怪的双到int转换行为在c

本文介绍了奇怪的双到int转换行为在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序显示了我在c ++中看到的奇怪的双到int转换行为:

The following program shows the weird double to int conversion behavior I'm seeing in c++:

#include <stdlib.h>
#include <stdio.h>

int main() {
  double d = 33222.221;
  printf("d = %9.9g\n",d);

  d *= 1000;
  int i = (int)d;

  printf("d = %9.9g | i = %d\n",d,i);

  return 0;
}



当我编译和运行程序时,我看到:

When I compile and run the program, I see:

g++ test.cpp
./a.out
d = 33222.221
d =  33222221 | i = 33222220

为什么i不等于33222221?
编译器版本是GCC 4.3.0

Why is i not equal to 33222221?The compiler version is GCC 4.3.0

推荐答案

浮点表示几乎从不精确(仅在特殊情况下) 。每个程序员都应该阅读:

Floating point representation is almost never precise (only in special cases). Every programmer should read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic

简而言之 - 您的电话号码大概是33222220.9999999999999999999999999999999999999999999999999999999999998(或类似内容),在截断后会变成33222220。

In short - your number is probably 33222220.99999999999999999999999999999999999999999999999999999999999999998 (or something like that), which becomes 33222220 after truncation.

这篇关于奇怪的双到int转换行为在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:22