How to separate a three-digit number in the C language?
We can separate a three-digit number using the modulo operation. Let’s assume the three-digit number we want to separate is called num.
- To extract the hundreds digit: dividing the number by 100 will give you the value of the hundreds digit.
- To extract the tens digit: use (num / 10) % 10 to obtain the value of the tens digit. Divide num by 10 first, then take the remainder when divided by 10.
- To isolate the units digit: You can obtain the value of the units digit by using num % 10, which is simply finding the remainder when num is divided by 10.
Here is a sample code:
#include <stdio.h>
int main() {
int num, hundreds, tens, units;
printf("请输入一个三位数:");
scanf("%d", &num);
hundreds = num / 100;
tens = (num / 10) % 10;
units = num % 10;
printf("百位数:%d\n", hundreds);
printf("十位数:%d\n", tens);
printf("个位数:%d\n", units);
return 0;
}
After running the program, the user inputs a three-digit number, which the program will then separate into hundreds, tens, and units places and output.