I've been struggling with this for days now......

Say the number entered is 12345

If the user wants to find the value of the 4th digit, which would be the 2....how can I do this???

He's counting his digits from right to left Walt.
So IMHO it has to be more something like this : (pseudocode)

number = 12345;
n = 4; //we seek the fourth digit from the right
num = number / 10^(n-1);
digitvalue = num % 10; //this we want

Ok so this is what I have so far. I can't figure out how to get it to work. What am I doing wrong? Oh and it's a she not he ;)

int main()
{
	int num = 0;
	int number = 0;
	int n = 0;
	int result = 0;


	cout << "Enter a number: ";
	cin >> number;
	cout << "Enter a digit position:";
	cin >> n;

	
	if ( 0 == number)
		{
		 cout << "0";
		}

	while (n-- > 1)
	{
	num = number / (10^n-1);
	result = num % 10;
	}


	cout << "\nThe value of this digit is: " << result << endl;
	system("Pause");
	
}

>>num = number / (10^n-1);

you have to use pow() function num number / pow(10,n)-1; The problem with that is if pow() returns 1 then the formula will get a divide by 0 error.

ok I had figured out I had to change it to Pow.....was getting that overload error.....i see what ur saying about it ending up dividing by zero.....but I dont know what Im doing....

#include <iostream>
#include <cmath>

using std::cin;
using std::cout;
using std::endl;

int main()
{
	int number = 0;
	int n = 0;
	int result = 0;

	cout << "Enter a number: ";
	cin >> number;
	cout << "Enter a digit position:";
	cin >> n;

	if ( 0 == number)
		{
		 cout << "0";
		}

	while (n-- > 1)
	{
	number = number / pow(10,(n-1.0));
	result = number % 10;
	}

	cout << "\nThe value of this digit is: " << result << endl;
	system("Pause");
	
}

>>number = number / pow(10,(n-1.0));
Its still incorrect. 1 is subtracted from the return value of pow(), not from n. See the formula in my previous post number = number / (pow(10,n) -1 );

He's counting his digits from right to left Walt.
So IMHO it has to be more something like this : (pseudocode)

number = 12345;
n = 4; //we seek the fourth digit from the right
num = number / 10^(n-1);
digitvalue = num % 10; //this we want

Interesting....
Dividing by 10, Mod'ing by 10. You just added the obvious power which was hers to think through. I tried not to take all the thinking out of the problem.

Comments
Yup, gotta make 'em think at some point
This article has been dead for over six months. Start a new discussion instead.