explain fragment of code

Can someone explain why the out out is 1035.840088
I figured it would be 1035.84
1
2
3
4
5
6
7
8
9
10
11
  #include<stdio.h>
#define mypm(zz) zz-1
main()

{
   float x,y=32.2;
    
    x=mypm(y*y);
    printf("%f\n",x);
     
 }
When working with floating-point numbers you need to expect small errors like that. If float doesn't have enough precision for your needs you might want to use double, or even long double.

You cannot even store the value 32.2 as a floating-point without getting rounding errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>

int main()
{
	float f = 32.2f;
	double d = 32.2;
	long double ld = 32.2l;
	
	std::cout << std::setprecision(100);
	std::cout << "32.2 as float:       " <<  f << '\n';
	std::cout << "32.2 as double:      " <<  d << '\n';
	std::cout << "32.2 as long double: " << ld << '\n';
}
32.2 as float:       32.200000762939453125
32.2 as double:      32.2000000000000028421709430404007434844970703125
32.2 as long double: 32.2000000000000000006938893903907228377647697925567626953125
Last edited on
Topic archived. No new replies allowed.