Here is a sample of source code
#include <iostream.h>
#include <conio.h>
#include <math.h>
int main()
{
int i=2,a;
a= pow(10,i);
int b=0;
b+=a;
cout<<b;
getch();
}
The ouput I expect is 100 as it is clear. But the compiler give 99 as output. Can anyone please explain what is the problem in the code and how it can b corrected to get 100 as output.
Change this line:
a = round(pow(10,i));
You can write the round function as:
int round(double r) {
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
NOTE: pow() returns a double, so the best way to avoid such problem is to make a double, not int.
pow(10,i) is 99.99999999999 then floored to integer a=99
You can create your own integer overloading of pow(int,int) also.
Good day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With