Hassaan Elahi
Hassaan Elahi

Reputation: 43

creating and calling function

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

Answers (2)

mayukhc
mayukhc

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

AlbertFG
AlbertFG

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

Related Questions