Jun 16, 2022 at 10:11pm UTC
Im trying to print on digit at a time for example, 123 would be
1
2
3
using an algorithim my proffessor is telling us to use but mines ends up printing 123 as
1
12
123.
Any close on what to do?
My code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
#include <math.h>
using namespace std;
void digit (int num)
{
int num2 = num;
int dc = 0;
int x =0;
int divisor = 0;
{
num=num/10;
dc++;
}
divisor = pow(10, dc);
while (dc < num)
{
num=num/10;
dc++;
}
divisor = pow(10, dc);
while (divisor > 0)
{
x = num2/divisor;
cout << x << endl;
x=x*divisor;
x=num2-x;
divisor=divisor/10;
}
}
int main ()
{
int num = 0;
cout << "Please enter a number: " ;
cin >> num;
digit(num);
cin.ignore();
cin.get();
return 0;
}
Last edited on Jun 16, 2022 at 10:35pm UTC
Jun 16, 2022 at 10:38pm UTC
number % 10 gets you the 1s place.
So if you combine % and /, you can get each digit (but this is actually backwards).
So it might be easier if you write a function to reverse the digits of an integer, then loop by printing (number % 10) then doing (number = number / 10) while number > 0.
Jun 16, 2022 at 11:24pm UTC
Thanks Ganado!!! It works now :)
Jun 17, 2022 at 8:32am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
void print( unsigned long long n )
{
if ( n > 9 ) print( n / 10 );
std::cout << n % 10 << '\n' ;
}
int main()
{
print( 1234567890112233ull );
}
1
2
3
4
5
6
7
8
9
0
1
1
2
2
3
3
But no, this is nothing like the (very longwinded) algorithm that your teacher required.
Last edited on Jun 17, 2022 at 8:36am UTC