0

So, I was using VScode to run my c++. Here is my code:

int main() {
    int value = 153;
    int output=0;
    string number = to_string(value);
    int exp = number.length();
    for (char n :number) output += pow(n-'0',exp);  
    cout << output;
}

The output I get from using "Run Code" is 152, which is wrong. The output from using debug is 153,which is right. Why would that happen?

tadman
  • 208,517
  • 23
  • 234
  • 262
totoma
  • 23
  • 3
  • 4
    Is it possible the floating point settings are different between your release and debug builds, like is fast math turned on in release? `ceil(pow(n-'0',exp))` might help. – Retired Ninja Jul 31 '20 at 20:00
  • This feels a lot like a very tiny rounding error. What are you trying to do here? Using `pow` to do string to number conversion is not the fastest way to do this. – tadman Jul 31 '20 at 20:01
  • 1
    This may help: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Retired Ninja Jul 31 '20 at 20:02
  • I was doing a codewars question which is Narcissistic Number. `ceil(pow(n-'0'), exp) `is working, thanks! – totoma Jul 31 '20 at 20:07
  • 4
    @totoma -- Advice -- Do not use floating point functions such as `pow` to do non-floating point solutions. If the goal of the program was to turn 153 into a string or from a string to an integer, there is no need to use `pow` for that -- just a simple modulus of 10 and repeated integer division or multiplication. – PaulMcKenzie Jul 31 '20 at 20:11
  • @PaulMcKenzie yeah, thanks a lot. The goal is to tell if a number is a positive number which is the sum of its own digits, each raised to the power of the number of digits. I was testing the main part. – totoma Jul 31 '20 at 20:18
  • What is the actual problem you're trying to solve? Why do you need to convert the number to a string? If you need to print the digits one by one (in the correct order) there are many other ways. – Some programmer dude Jul 31 '20 at 21:03
  • string.length() returns a size_t (not an int). you also should check inputs/output to pow (does not return an int to add to output) and ceil (does not return an int for exp). – 2785528 Jul 31 '20 at 21:11

0 Answers0