If it is possible to take last 2 digits of a 4 digit number using C++?
Please help me...!!
Of course there is!
Using simple math:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <cmath>
using namespace std;
int get_last_nums(int num)
{
int major = floor(num/100.0);
double decimal = num/100.0;
int last_two = (decimal-major)*100;
return last_two;
}
int main()
{
int n = 1234;
int last_two_num = get_last_nums(n);
cout << "Last two nums: " << last_two_num << endl;
return 0;
}
|
There are other methods
but they are more complex. This
is by far the simplest IMHO and also works for numbers more than 4 digits.
Last edited on
question. does the modulu (%) work too?
Yes it does, you need to take modulo 100. (I totally forgot about that lol)
E.g 1250%100 = 50.
Last edited on