Watch this simple program, strange thing happens?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
User avatar
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Watch this simple program, strange thing happens?

Post by ImLazy » Thu Aug 18, 2005 11:47 am

Code: Select all

#include <stdio.h>
int main(){
  float a;
  int b;
  return 0;
When I input 1.05, the output is 104!!! Why?
I have tried VC++ 6.0 and MinGW 3.1.0-1. They give the same output.
I stay home. Don't call me out.

A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Thu Aug 18, 2005 1:09 pm

This looks like floating point precision errors. float datatype is not very precise. If you use double instead of float, you will get 105.

User avatar
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Post by Martin Macko » Thu Aug 18, 2005 9:03 pm

Probably, the best one could do, is to avoid any floating point arithmetics (float and also double) and use just ints as long as possible. Floating point precision errors may give really strange results sometimes.

Post Reply

Return to “C++”