0
#include <iostream>
#include<cmath>

using namespace std;

int main(){

    int input;
    int mod = 1;
    int x;
    cout << "Please Enter a four digit Integer: ";
    cin >> input;

    for(int i = 3; i >= 0; i--){
        mod = pow(10,i);
        x = input / mod;
        input = input % mod;
        cout << x << "  ";
    }

    return 0;
}

this is a programming exercise. we are asked to get a 4 digit input from keyboard and display the input with 2 whitespaces in between the number. the problem is with the pow(10,i) function. when i checked what the function gives to the "mod" var is when i is equal to 2, it results to 99 but not 100 because 10 raised to 2 is 100. can you help me debug the code? Thank you

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
gbigz
  • 1
  • 3
    You do know that `std::pow` operates on floating point numbers, not integers, right? – UnholySheep Jun 27 '18 at 14:57
  • 2
    *pow() function gives an error* and the error is what exactly? – Borgleader Jun 27 '18 at 14:57
  • [`pow()`](https://en.cppreference.com/w/c/numeric/math/pow) returns a real number that when stored in the floating-point format is not exact. Your code should use only integer values and computing the powers of `10` are not difficult. – axiac Jun 27 '18 at 14:57
  • pow(10,2) = 99 it should be 100 @Borgleader – gbigz Jun 27 '18 at 14:59
  • [Cannot repro](http://coliru.stacked-crooked.com/a/cafd84b9eead7e4d) – Borgleader Jun 27 '18 at 15:04
  • @KevinBigay `pow(10,2) ~= 100.00`. The troublemaker is the assignment of a real value to an integer variable. Don't use real numbers, you don't need them. Stick with integers. – axiac Jun 27 '18 at 15:09
  • to those who helped me. thank you so much. i found a way to make the pow(10,2) become 100 not 99. i used the pow(10,2) as a parameter for the ceil() function @Borgleader – gbigz Jun 27 '18 at 15:10
  • @gibgz That is still dangerous. Your problem is that floating point math may give you 99.999994 or 100.000003 or similar. The latter could produce incorrect results with your method. Just round to the _nearest_ integer, i.e. [std::round](https://en.cppreference.com/w/cpp/numeric/math/round). – Max Langhof Jun 27 '18 at 16:14
  • BTW, on most platforms, `10 * 10` is more efficient and accurate than `pow(10,2)`. Minimally there is a function call involved (which may cause the processor to reload the instruction pipeline). The multiplication usually involves a few assembly instructions and is more accurate. Although a smart compiler could replace the expression with 100. – Thomas Matthews Jun 27 '18 at 16:35

0 Answers0