-2

The Problem Statement is:

  1. You've to display the digits of a number.
  2. Take as input "n", the number for which digits have to be displayed.
  3. Print the digits of the number line-wise.
#include<iostream>
#include<cmath>

using namespace std;
 
int main(){
    int n;
    cin>>n;
    int nod = 0;
    int temp = n;
    while(temp != 0){
        temp = temp / 10;
        nod++;
    }
    int  div = (int)pow(10, nod - 1);
    while(div != 0){
        int dig = n / div;
        cout<<dig<<endl;
        n = n % div;
        div = div / 10;
    }
    return 0;
}

enter image description here

For input 65784383, the expected output is:

6

5

7

8

4

3

8

3

However the ouput from the program is not as expected. Where did it go wrong?

t.niese
  • 39,256
  • 9
  • 74
  • 101
pi-π
  • 93
  • 5

1 Answers1

0

Maybe you get wrong output, I don't know, you didn't say why you think there is something wrong with the code.

I do get correct output here: https://godbolt.org/z/xsTxfbxEx

However, this is not correct:

int  div = (int)pow(10, nod - 1);

pow is not for integers. I suggest you to read documentation and this, and consider what happens when you truncate a floating point number to an integer.

To print linewise digits of a number given by the user all you need is this:

#include <iostream>
#include <string>
int main() {
    std::string input;
    std::cin >> input;
    for (const auto& c : input) std::cout << c << "\n";
}

Maybe you consider this cheating and insist on doing the maths. Then collect the digits from back to front and print in reverse order, thats much simpler:

#include <iostream>
#include <vector>
int main() {
    int n;
    std::cin >> n;
    std::vector<int> digits;
    while (n) {
        digits.push_back(n % 10);
        n /= 10;
    }
    for (auto it = digits.rbegin(); it != digits.rend(); ++it){
        std::cout << *it << "\n";
    }
}

PS: Do not use c-style casts like you do here

 int  div = (int)pow(10, nod - 1);
           //^^

Actually it is superfluous here, because assigning a floating point number to an int already does the truncation. Though, also in general c-style casts are to be avoided. As far as I know, the only reason they are allowed is backwards compatibility. If you do need to cast you should use static_cast. Most of the time c-style casts merely silence compiler warnings or errors and hide problems in the code.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185