+ 1

A weird number was outputted

Why it appear a strange number(5.3649e-0.7)during subtraction for two float numbers(in c++)? The number should be zero but it didn't. And the total sum was not effected at all. Could anyone tell me why it happens?

8th Jan 2017, 3:53 AM
Queven
Queven - avatar
7 Antworten
+ 5
we can tell what its wrong, if you show the code. But I asume that one variable wasn't assigned and had garbage default value.
8th Jan 2017, 3:56 AM
Nahuel
Nahuel - avatar
+ 4
That is because binary representation of floating point. https://en.wikipedia.org/wiki/Floating_point You will have to check a library, or truncate the value to 2 decimals, that mights work if you get them to string and then show index 0, 1 (point), 2 , and 3
8th Jan 2017, 4:46 AM
Nahuel
Nahuel - avatar
+ 3
Indeed, You are adding stuff to a not initialized var. float sum = 0;
8th Jan 2017, 4:15 AM
Nahuel
Nahuel - avatar
+ 1
Here's the code. #include <iostream> using namespace std; int main() {float sum; float y=2.8; for(int x=0;x<14;x++){ sum+=y; cout<<y<<endl; y-=0.4;} cout<<sum; return 0; }
8th Jan 2017, 3:59 AM
Queven
Queven - avatar
+ 1
I think the variable sum isn't initialised so it has some garbage value. I think so!!
8th Jan 2017, 4:54 AM
Srinivasan Madabhooshi Padmanabha
Srinivasan Madabhooshi Padmanabha - avatar
0
@Nahuel Ovejero thx:) But the problem happened on the var y which is initialized. I'm really curious about that. :)
8th Jan 2017, 4:29 AM
Queven
Queven - avatar
0
gotit!!Thx :)
8th Jan 2017, 4:53 AM
Queven
Queven - avatar