Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
if you are given an integer like 2003, and you want to give output taht says it has 4 digits and the 4th digit is 3, how do you approach it without processing the value as character?

You'll have to process it as a character, either directly or indirectly..
If you want to do it directly, you could have the variable input as a char.
Otherwise, use an inttochar(int) function, or write your own (the simplest way would be to take the number, modulus 10^n, and round down for each digit).AKhalifman@hotmail.com

There are several ways; here is one that uses the std::log() function C++ has which takes floats and doubles and I'm not sure what else.
#include <iostream>
int main () {
using namespace std;
double x=2003,y=10;
int digits = 1 + int(log(x)/log(y));
int units_digit = int(x) % 10;
cout << "digits: " << digits << endl;
cout << "units digit: " << units_digit << endl;
}Make sure it's a +ive number before you take it's log.

Wolfbone, your method was ingenious!! what if it wanted the third digit of 2003? or 2nd digit? or first?

Define a recursive function (this - simplest - one counts digits of n from right to left):
unsigned mth_digit(unsigned n,unsigned m) {
if (m == 1) return (n % 10);
else return mth_digit((n-(n%10))/10,m-1);
}BTW if you're going to use this stuff in earnest, you should maybe be more careful with typing, range checking and casting of integers - eg use static_cast<unsigned>(x) etc. - RTFC++M ;-)

Wolfbone, the last answer you gave is a little hard to comprehend! can you expand on your first answer(the log function) to answer my second question? because it's much easier! or at least is there an easier way?

There is not really any easier or more natural way than recursion and you should not find it difficult to understand if you follow it through in your head or with the assistance of pen and paper but it is just as easy to write it iteratively - in a 'while' loop for example.
The log function is only useful here for finding the total number of digits of n initially, but you can then use it to count digit places from left to right, until you reach the digit you want the value of. Look carefully at the arguments to the mth_digit() function in the 'else' statement above and you will see what needs to happen inside the loop.
I would be more explicit but if this is homework you probably ought to understand exactly how it is working, which you can only do by constructing the code yourself. At least have a go at it before you post again! :-)

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |