This code finds the first,last and # of digits of an integer. Problem is using an if statement to find the # of digits only works up to nine digits. suggestions on a better way to do this?
#include <iostream>
#include <string>
using namespace std;
int first_digit (int n)
{
const int base = 10;
int x;
do
{
x = n % 10;
}
while (n /= base);
return x;
}
int last_digit (int n)
{
int x;
{x = n % 10;}
return x;
}
int digits (int n)
{
n = abs(n);
if (n < 10) return 1;
else if (n < 100) return 2;
else if (n < 1000) return 3;
else if (n < 10000) return 4;
else if (n < 100000) return 5;
else if (n < 1000000) return 6;
else if (n < 10000000) return 7;
else if (n < 100000000) return 8;
else if (n < 1000000000) return 9;
else
return 10;
}
int main()
{int input;
cout << "Please enter a number: ";
cin >> input;
cout << "The first digit is ";
cout << first_digit (input) << endl;
cout << "The last digit is ";
cout << last_digit (input) << endl;
cout << input << " has " << digits (input) << " digit(s)." << endl;
system ("pause");
return 0;
}
At twelve digits you get close and/or reach the max size of an int (232 on a 32 bit system, 264 on a 64 bit system). Use longlongint or other larger data types for bigger numbers.
#include <limits>int main()
{
std::cout << "The maximum number of decimal digits an int can hold on this system is "
<< std::numeric_limits<int>::digits10 << '\n' ;int input;
cout << "Please enter a number: ";
cin >> input;
cout << "The first digit is ";
cout << first_digit (input) << endl;
cout << "The last digit is ";
cout << last_digit (input) << endl;
cout << input << " has " << digits (input) << " digit(s)." << endl;
system ("pause");
return 0;
}