The Following User Says Thank You to bandora For This Useful Post: | ||
|
2013-09-23
, 04:46
|
Posts: 1,141 |
Thanked: 781 times |
Joined on Dec 2009
@ Magical Unicorn Land
|
#12
|
Oh, now if you are stuck trying to figure out what the length of "[string 2]" would be, since that's an integer/float/double variable, I would approach it like this:
You know that the amount of digits in the number determines the length.
You know in decimal counting systems, each digit is one greater multiple of 10, essentially.
For an integer, then, you can figure out how many digits it will be by dividing it by ten until it becomes zero (as C++ will floor decimal results for intergers).
For every power of ten it has, you add one more to your digits counter.
With a little bit of thinking, it should be possible for you to figure out how to convert the above into code. If you can't after a while, I can show you what I've written to do so. (Hint, either a loop, or a series of if/else-if checks with less/great -than comparisons.)
With a little more thinking, you can adapt such approaches to floats/doubles as well.
There's other ways too, of course, usually involving using other fancy C++ classes and stuff, if that's the route you want to go.
The Following User Says Thank You to stlpaul For This Useful Post: | ||
|
2013-09-23
, 08:16
|
Posts: 2,225 |
Thanked: 3,822 times |
Joined on Jun 2010
@ Florida
|
#13
|
You should become a teacher, you have a great way of suggesting solutions without flat-out telling the answer. This counting function sounds exactly like an exercise I did while learning programming.
And be sure it can handle the number 0 (which still takes 1 character to print on-screen). It is an easy one to miss when you're focusing on testing bigger numbers.
|
2013-09-23
, 08:31
|
|
Posts: 6,447 |
Thanked: 20,981 times |
Joined on Sep 2012
@ UK
|
#14
|
And be sure it can handle the number 0 (which still takes 1 character to print on-screen). It is an easy one to miss when you're focusing on testing bigger numbers.
Using standard library functions, depending on what you know about the input number type, a perhaps easier mathematical approach could be to use log10(i)+1 but it's still up to you to handle negatives, floats, etc.
Taking the "convert it to a string and count the characters" approach, in C++11, my everyday choice would be to simply do: to_string(i).length()
|
2013-09-23
, 20:09
|
Posts: 1,141 |
Thanked: 781 times |
Joined on Dec 2009
@ Magical Unicorn Land
|
#15
|
Honestly I can't describe how much I appreciate all your help guys! I keep on saying this over and over again.. This is why I really love this community! Very helpful in everyway.
FarahFa.com