Hi I am very new to c++ programming.I am just trying to check whether the number is Armstrong number. Please see my code below.
This program works fine for all the numbers but when I give 153, which is Armstrong number is getting printed as not an Armstrong number.
Also armstrong=armstrong+pow((temp%10),counter); gets evaluated as 124 instead of 125 for 5^3.
Eventhough I have found better methods now. I still want to know why this code isn't working.
#include <iostream>
#include <math.h>
using namespace std;
int armstrong(int n)
{
int counter=1;
int temp =n;
int armstrong=0;
while(n>10)
{
n=n/10;
counter ++;
}
while(temp>=1)
{
armstrong=armstrong+pow((temp%10),counter);
temp=temp/10;
}
return armstrong;
}
int main()
{
int n=0;
cout << "Enter the number to check!" << endl;
cin >> n;
armstrong(n);
if(n==armstrong(n))
{
cout << "The number is armstrong"<< endl;
}
else
{
cout<< "The number is not armstrong"<<endl;
}
return 0;
}
> but when I give 153, which is Armstrong number is getting printed as not an Armstrong number.
> Also ... gets evaluated as 124 instead of 125 for 5^3.
The floating point representation is an inexact representation of a real number; because of its inexactness, computations involving floating point values are subject to rounding errors.
Thanks a lot! It works now. since the Pow function inside the math.h converts the int to double value. The conversion and rounding led to surprising results.
Correct?
Also is there any best practice to avoid this kind of errors in future