Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c++ - Why does this double to int conversion not work?

I've been thoroughly searching for a proper explanation of why this is happening, but still don't really understand, so I apologize if this is a repost.

#include <iostream>
int main()
{
    double x = 4.10;
    double j = x * 100;

    int k = (int) j;

    std::cout << k;
 }

 Output: 409

I can't seem to replicate this behavior with any other number. That is, replace 4.10 with any other number in that form and the output is correct.

There must be some sort of low level conversion stuff I'm not understanding.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

4.1 cannot be exactly represented by a double, it gets approximated by something ever so slightly smaller:

double x = 4.10;
printf("%.16f
", x);  // Displays 4.0999999999999996

So j will be something ever so slightly smaller than 410 (i.e. 409.99...). Casting to int discards the fractional part, so you get 409.

(If you want another number that exhibits similar behaviour, you could try 8.2, or 16.4, or 32.8... see the pattern?)

Obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...