Home > database >  I wrote this C code for Palindrome numbers but the power function is giving me one less value in t
I wrote this C code for Palindrome numbers but the power function is giving me one less value in t

Time:11-30

int main(){
    int n, val, i,sum(0),temp,m(0);
    cout<<"Enter the number: ";
    cin>>n;
    temp=n;
    while(n>0){
        n/=10;
        m  ;
    }
    n=temp;
    while(n>0){
        m--;
        i=n%10;
        val= i*pow(10,m);
        cout<<"Power: "<<val<<endl;
        sum=sum val;
        n/=10;
    }
    if(temp==sum){
        cout<<"Palindrome";
    }
    else{
        cout<<"Not Palindrome";
    }
    return 0;
}

Here in this part:

        val= i*pow(10,m);
        cout<<"Power: "<<val<<endl;

If m=2 and i=1 then this should give 100 but I'm getting 99 as output. This is happening only for the first val and for the other it shows the perfect value

enter image description here

Can anyone tell me what I'm doing wrong

CodePudding user response:

pow is a floating point function that if poorly implemented by the C standard library, can fail to return the best possible double even with an integral exponent. You might have better luck with one of the std::pow overloads but even then you're at the mercy of the quality of the C standard library.

Fortunately though you don't need pow at all!

In your first loop, where you set the starting value for m, do the same thing with val: setting it first to 1 then using val *= 10; in the loop body.

Then in the second loop apply val /= 10 as appropriate.

Take care not to overflow int: it can have a range as small as -32767 to 32767 (C 20 widens the lower limit to -32768). It might be an idea to use a long or a long long instead.

CodePudding user response:

Just as a side not and unrelated to your "power" problem.

You can read the number as a string. Then you can compare this string with its reversed version. If equal, then you have a Palindrome else not. The standard approach is to use reverse iterators for that.

In the end, you will have only 3 statements in main. And it is not complicated . . .

Please see:

#include <iostream>
#include <string>

int main() {
    std::cout << "\nEnter a number: ";
    if (std::string number{}; std::cin >> number)
        std::cout << (number == std::string(number.rbegin(), number.rend()) ? "Palindrome" : "No palindrom") << '\n';
}

  •  Tags:  
  • c
  • Related