How to get the first two digits of int number in C++

2 Answers

0 votes
#include <iostream>  

   
int main() {  
    int n = 840172;  
       
    std::cout << n << "\n";  
       
    int tmp = n, first_two_digits = n; 
    while (n) {
        first_two_digits = tmp;
        tmp = n;
        n /= 10;
    }   
         
    std::cout << first_two_digits;  
       
    return 0;
}  
   
   
   
   
/*
run:
   
840172
84
   
*/

 



answered Jan 15, 2021 by avibootz
0 votes
#include <iostream>  
#include <cmath> 
   
int main() {  
    int n = 840172;  
       
    std::cout << n << "\n";  
       
    int totaldigits_minustwo = (int)log10(n) - 1; 
  
    int first_two_digits = (int)(n / pow(10, totaldigits_minustwo));
         
    std::cout << first_two_digits;  
       
    return 0;
}  
   
   
   
   
/*
run:
   
840172
84
   
*/

 



answered Jan 15, 2021 by avibootz

Related questions

1 answer 170 views
1 answer 165 views
2 answers 263 views
1 answer 139 views
2 answers 188 views
188 views asked Jan 14, 2021 by avibootz
1 answer 171 views
...