[英]How can I separate an integer into muliple digits?
I have a remainder function that finds that modulo of a number then a divider function to divide that number. 我有一个余数函数,该函数先求一个数字的模,然后求一个除法器函数对该数进行除法。 My program isn't working the way I need it to.
我的程序无法按我需要的方式工作。 For example if I put in 2502 as my number, I should get the output of : 2 5 0 2. I need to be able to store the value through each iteration, so for example:
例如,如果我输入2502作为我的数字,我应该得到:2 5 0 2的输出。我需要能够在每次迭代中存储该值,例如:
number: 123
123 % 10 = 3 //last digit
Number: 123 / 10 = 12
12 % 10 = 2 //second digit
Number: 12 / 10 = 1
1 % 10 = 1 //first digit
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
while(num != 0){
int rem = num % 10;
return rem;
}
}
int Div(int num){
while(num != 0){
int div = num / 10;
return div;
}
}
The idea here is pretty simple, but there are some subtleties. 这里的想法很简单,但是有一些细微之处。 Here's some pseudo code.
这是一些伪代码。 You'll need to convert to C.
您需要转换为C。
num = 9934; // or get it from input
do {
rem = num % 10; // this gives you the lowest digit
num = num / 10; // divide by 10 to get rid of that lowest digit
print rem;
} while (num != 0);
I use a do ... while
loop so the output will be correct if the user enters 0. 我使用
do ... while
循环,因此如果用户输入0,输出将正确。
If you code this up and run it, you'll notice that it prints the digits in reverse order: 4 3 9 9
. 如果您对此进行编码并运行,您会注意到它以相反的顺序打印数字:
4 3 9 9
。 So you'll need some way to reverse the digits before you output them. 因此,在输出数字之前,您需要某种方式来反转数字。 Three possible ways are:
三种可能的方式是:
您也可以将其转换为字符串,然后再转换回该字符串的元素,但请记住“ \\ 0”
You can simply use this function , it return the number of digits passing by argument 您可以简单地使用此函数,它返回参数传递的位数
size_t ft_cnbr(int n)
{
size_t count;
count = 1;
if (n < 0)
{
count++;
n = -n;
}
while (n > 9)
{
n = n / 10;
count++;
}
return (count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.