Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpredictable Output in C++

Tags:

c++

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.

like image 556
Arun Sharma Avatar asked May 18 '26 10:05

Arun Sharma


2 Answers

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.

like image 115
Rafi Kamal Avatar answered May 21 '26 00:05

Rafi Kamal


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.

like image 22
huseyin tugrul buyukisik Avatar answered May 20 '26 22:05

huseyin tugrul buyukisik