0

What can I do to compare two variables of type float accurately in C++, one being initialized at the time of declaration and the other being computed through the program?

When I am comparing two variables having value either 0.5 or 0.25, the program is showing the desired output but when I am comparing two variables having value either 0.333333 or 0.666667, the program is not showing the desired output. Will you please tell me where I am going wrong? Please help me in writing the correct piece of code. I am a novice and it will be a great experience to learn from you. Thank you for your concern. Here is the code with some of the outputs:

  1. OUTPUT 1
  2. OUTPUT 2
ThisaruG
  • 3,222
  • 7
  • 38
  • 60

1 Answers1

0

My english speaking is not well, I hope you can get me. Firstly, you must know about the float type, a variable type has two defines, they are accuracy and range. A float type has 32 bit range. 1 bit is symbol, 8 bits are exp and 23 bits are mantissa.So a float type variable has an accuracy of 2^23 = 8388608 that total 7 bit.But generally we use that or some console output that just with 6 bit accuracy, so your 'a' variable is 0.6666670(7 bit) and your 'b' variable is 0.6666666(7 bit).Obviously they are not equal.You can try use printf() function to output them with parameter of bits limit,i think you can get the real value of them. I hope i could help you.

musa
  • 11
  • 3