+ 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?
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.
+ 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
+ 3
Indeed, You are adding stuff to a not initialized var.
float sum = 0;
+ 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;
}
+ 1
I think the variable sum isn't initialised so it has some garbage value. I think so!!
0
@Nahuel Ovejero thx:)
But the problem happened on the var y which is initialized. I'm really curious about that. :)
0
gotit!!Thx :)