Program evaluating 5^3 = 124

This is the strangest thing I have in my entire C++ career. I am writing a program to find Armstrong numbers and the following code is a snippet from the program. It adds up individual digits of 153 to 152.


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
     int num = 153; 
            
            int temp2 = num;
            
            while(temp2 >= 1)
            {
                int temp = temp2 % 10;
                vect.push_back(temp);
                temp2 = temp2 / 10;
            }
            
            
            int HOLDER2 = 0;
            
            for(int k = 0; k < vect.size(); k++)
            {
                 cout <<  vect[k] << endl;
                 
                 HOLDER2 = pow(vect[k], 3);
                 cout << HOLDER2 << endl;  //outputs 124 for 5^3
                 vect2.push_back(HOLDER2); //vect2 contains cubes of individual 
                                           //digits                                          
                  
                
            }

When you store a floating-point number (return type of pow) in an integer variable (HOLDER2), the value is truncated, not rounded.

Try printing the full result of your pow() call: cout << setprecision(50) << pow(vect[k], 3); -- I bet it is 124.9999999...
Cubbi, thanks for the reply. It outputs 125. I ran the same code on Ideone (the online compiler) and got the correct result. Something is not right with my Dev C++
Topic archived. No new replies allowed.