Write a program that reads an integer and prints its digits. For instance, if the user
enters -341670, the program should print the following lines:
Digit 1 is: 3
Digit 2 is: 4
Digit 3 is: 1
Digit 4 is: 6
Digit 5 is: 7
Digit 6 is: 0
so far i got this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <cmath>
#include <math.h>
usingnamespace std;
int main() {
int n,d;
cout << "Enter the number.";
cin >> n;
if ( n == 0)
d=1;
else
d = 1 + log10(abs(n));
cout << n << " has " <<d <<" digits."<<endl;
I'm not sure what you were trying to do with abs and logs. The modulus method would be the best. Remember the digits you are talking about are from the decimal base. So if we use the modulus of 10 ( decimal ) that will give us the right most digit. We can then remove that digit by dividing by 10 again its in decimal base.
is there a simpler way to do this cuz i dont think we learn array yet.. or any method u posted.
and i was given a hint:
Find the length of the integer first, that is the number of digits. In the above case, the length of -341670 is 6. Then to get the first digit compute 341670 / 10^5 = 3. Then 341670 - 3*10^5 = 41670. Now apply the above steps to 41670.
yeah that would work too. Look like d is your amount of digits
So from there you want to follow the formula provided it would look like this
1 2 3 4 5 6 7 8
int last_digit = 0;
int power = pow( 10 , d );
for( int i = 0; i < d; ++i )
{
last_digit = n / power;
n -= last_digit * power;
std::cout << "Digit " << i + 1 << " is : " << last_digit << std::endl;
}
Sorry that was my fault. line 18 should be d - 1 instead of d. Reason being to find the left digit in 100 we would divide by 10 to the second not ten to the third. 10^ == 100 and 100 / 100 = 1. Also don't forget if it is a negative value to negate it to a positive. ex -341670 you wan't to make it 341670 the negative sign doesn't affect the digits but it will mess up your calculations. Also line 11 should be if n < 10 instead of == 1 after you negate.
Also after checking the formula you mentioned earlier it should be
#include <iostream>
#include <cmath>
usingnamespace std;
int main() {
int n,i,d;
cout << "Enter the number.";
cin >> n;
if( n < 0 )
n = - n;
if ( n < 10 )
d=1;
else
d = 1 + log10(abs(n));
cout << n << " has " << d <<" digits."<<endl;
int digit=0;
int power = 0;
for (int i=0; i < d; i++)
{
power = pow( 10 , d - 1 - i );
digit = n / power;
n -= digit * power;
cout << "Digit " << i+1 << " is: " << digit<<endl;
}
return( 0 );
}
Though might I suggest you use better variable names instead of d and n.
Maybe try input for n and number_of_digits for d?