Today’s Code of the Day is about how to find the digit of a number at a given position. I decided to go with the C / C++ programming languages to time, but you can easily translate the algorithms to other languages.
C Code.
#include
#include
// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum( int num, int digit ){
num /= pow( 10, digit );
return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec( double dec, int digit ){
dec *= pow( 10, digit );
return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals( double dec ){
return dec - (int)dec;
}
Example:
Input File
// Programmed by Larry Battle, bateru.com/news
// Date: April 26, 2011
// Purpose: To demonstrate how to get a digit by a position index.
#include
#include
int getDigitFromNum( int num, int digit ){
num /= pow( 10, digit );
return num % 10;
}
int getDigitFromDec( double dec, int digit ){
dec *= pow( 10, digit );
return ((int)dec) % 10;
}
double getDecimals( double dec ){
return dec - (int)dec;
}
void main(){
double dec = 1234.56789;
printf( "\n%d", getDigitFromNum( (int)dec, 0 ));
printf( "\n%d", getDigitFromDec( dec, 2 ));
printf( "\n%f", getDecimals( dec ));
}
Output:
4
6
0.567890
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…