Problem understanding something FLOAT

I am new to C++ so please don’t flame me :)

I wrote a simple prog. to test this course but something isn’t really working well and I can’t figure out why…


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<string>
#include <iomanip> // for setprecision()
using namespace std;

main()
{
cout<<setprecision(7); //7 decimals
float v = 1;
float j = 3;
float cc;
cc = v/j;

//TEST with FLOAT NUMMERS
float ff = 0.3333333; // 7 decimals as set in "setprecusion(7);"

if(cc<ff) {
cout<<"cc is smaller then ff"<<endl;
}
else if(cc>ff) {
cout<<"cc is bigger then ff"<<endl;
}
else{
cout<<"cc equals to ff"<<endl;
}
cout<<cc<<" = cc"<<endl;
cout<<ff<<" = ff"<<endl;

return 0;
}

The output gives me that cc is bigger than ff…
I don’t understand why as I set precision to 7 and my var ff has also 7 decimals.
They should both be equal to eachother.

Any suggestions where I made an error?
Thanks!!
setprecision changes how the number is printed. It does not affect the actual numbers and how they are compared.
Last edited on
Its not actually performing float division
Try changing
1
2
float v = 1.0;
float j = 3.0;


Then check it.
Last edited on
@hacker804
v and j are floats so it is performing float division.
I did both (originally it was
1
2
float v = 1.0;
float j = 3.0;

I tested it with 1 and 3 and had the same result as I defined them as floats.

Peter87 is absolutely correct: what you see isn't what you actually get...
I have set cout<<setprecision(30) and I get different numbers after the 7th digit.

I guess I need to be careful using == when comparing floats :)
Yes, testing equality on floating point numbers is not to recommend. What you could do is to check if two numbers are almost equal.
1
2
3
4
if (std::abs(cc - ff) < a_very_small_number)
{
	// Almost equal.
}


If you want 7 decimals precision you can use 0.0000001 as the value of a_very_small_number.
Ha, nice work around.
Thanks Peter!
Topic archived. No new replies allowed.