![](/img/trans.png)
[英]How can I display integer that has 2 or more digits as a string?
[英]How can I separate an integer into muliple digits?
我有一個余數函數,該函數先求一個數字的模,然后求一個除法器函數對該數進行除法。 我的程序無法按我需要的方式工作。 例如,如果我輸入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;
}
}
這里的想法很簡單,但是有一些細微之處。 這是一些偽代碼。 您需要轉換為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);
我使用do ... while
循環,因此如果用戶輸入0,輸出將正確。
如果您對此進行編碼並運行,您會注意到它以相反的順序打印數字: 4 3 9 9
。 因此,在輸出數字之前,您需要某種方式來反轉數字。 三種可能的方式是:
您也可以將其轉換為字符串,然后再轉換回該字符串的元素,但請記住“ \\ 0”
您可以簡單地使用此函數,它返回參數傳遞的位數
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.