0

I have written a code. I am getting an wrong or unexpected answer form the code. The value of 2nd index of the array named arr should be 800 but it is showing 799. Other values are right.

Here is my C++ code:

#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>

using namespace std;

int main() {
  int n = 9876, count = 0, temp, size = (int) to_string(n).length();
  vector<int> arr;

  for (int i = 0; i < size; i++) {
    temp = (n % 10) * pow(10, i);
    arr.push_back(temp);
    n /= 10;
    cout << arr[i] << " ";
  }

  return 0;
}

The output of the program is: 6 70 799 9000

Here the third number is 799 but I think it should be 800

Why I'm getting this wrong answer?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Satyajit Roy
  • 517
  • 1
  • 5
  • 18
  • 1
    Use `round()` to convert the floating point number to the nearest integer rather than rounding down. – Barmar Feb 18 '22 at 20:53
  • You're dealing with floats, and that 799, is actually determined to be, before becoming an integer, 799.99999999... etc. – Bib Feb 18 '22 at 20:53
  • 1
    The function `pow` should be for experts only. I see so many misuses of it by beginners that the function should not be taught in courses! For integers, use a loop. For squaring `double` values, multiply the value by itself. The `pow` is for very special uses, I nearly never used it in 20 years of programming. – prapin Feb 18 '22 at 20:58
  • @SatyajitRoy -- Do not use floating point functions such as `pow` to solve integer-based problems. Your program is instantly broken by using `pow`, and it doesn't matter if `pow` just happened to give you the right value. There are implementations of `pow` where you will *not* always get the correct results, such as [this](https://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os) – PaulMcKenzie Feb 18 '22 at 21:06
  • The other comments make it clear that you shouldn't use pow. However, there is a simple algorithm that you can use to compute the power of an integer efficiently and accurately. Other than the [code](https://stackoverflow.com/a/17504209/10913049), you might also want to learn the [algorithm](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) itself. – Harsh Motwani Feb 18 '22 at 21:11
  • 1
    Before the `for` loop, insert this statement: `int power = 1;` at the end of the loop, insert `power * = 10;`. Your `temp` statement then becomes: `temp = (n % 10) * power;` – Thomas Matthews Feb 18 '22 at 21:16
  • Another technique is to read the input as a string. You can treat the string as an array to access the digits. – Thomas Matthews Feb 18 '22 at 21:20

0 Answers0