Reputation: 43
while working on a module i came across a problem and could not figure out the solution to the problem. here is the question . program will get the input number and position from the user output the digit which is is at that position. for example if number = 256314 and position = 0 then output should be "2" if number = 1256985 and position = 3 then output should be "6" here is my code
#include <iostream>
#include <cmath>
using namespace std;
int returnDigitAtPosition(int &position,int &totaldigits,int &number)
{
{
int positiondigit = number/pow(10,(totaldigits - position));
positiondigit = positiondigit % 10;
return positiondigit;
}
}
int main()
{
int number = 0,position = 0,digit = 0;
cout << " Enter the number : ";
cin>>number;
cout<<" Enter the position : ";
cin>>position;
/*cout<<" Enter the digit : ";
cin>>digit;*/
int totaldigits = log(number);
int DigitAtPosition = returnDigitAtPosition(position,totaldigits,number);
cout<<DigitAtPosition;
}
Upvotes: 0
Views: 90
Reputation: 1057
Change two lines,your code will work:
int positiondigit = number / pow(10, (totaldigits - position-1));
and
int totaldigits = log10(number)+1;
Upvotes: 0
Reputation: 157
try this:
#include <iostream>
#include <string>
using namespace std;
int main(){
int position;
string number;
cout << " Enter the number : " << endl;
cin >> number;
cout << " Enter the position : " << endl;
cin >> position;
cout << number[position] << endl;
}
receiving the number as a string will accept the number regardless the length of it.
Upvotes: 1