我有一个任务(目前正在研究循环语句,所以我处于初学者阶段),要求编写一个程序来反转整数,因此它必须具有 do
语句。
输出应该是(示例):
Enter a number: 4568 The reversal is: 8654
Please put in mind that since I'm following my book so far I've studied and know the very basics + selection and loop statements. I have very limited choices so no arrays.
The book suggests to make a do loop to divide repeatedly the number by 10
until it reaches 0
this is what I did so far (code not completed) :
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
x = n % 10;
printf("%d",x); /*outputs the last number digit in the first place*/
do{
....
n /= 10; /* for example if I divide the number 56222 by ten the output would come out as
5622 562 56 5*/
....
}while (n!=0);
return 0;
}
我找到了一种方法,可以将最后一位数字放在第一位,如您所见,但是 在这个非常有限的选择下,我正在努力弄清楚如何在将数字反复除以 10 后反转其余的数字。
我应该在 do 语句中放入什么? 非常感谢。
最佳答案
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
int rev = 0;
do{
x = n % 10;
rev = rev * 10 + x;
n /= 10;
}while (n!=0);
printf ("%d", rev);
return 0;
}
here you need a new integer rev whose value is 0 initially. Lets take example of 432
n = 432
when you do x = n % 10 x = 2
so when you do rev = rev * 10 + x rev is 0 and value of rev will be 2
n /= 10 make n = 43
-->so in the next iteration
n = 43 x = n % 10 results in x = 3
rev value now is 2
so rev = rev * 10 + x results in 2 * 10 + 3
so rev = 23
n /= 10 results in n = 4
-->in the last iteration n = 4 x = n % 10 results in x = 4 rev value now is 23
so rev = rev * 10 + x results in 23 * 10 + 4 so rev = 234
n /= 10 results in n = 0
so when you print rev you get the answer 234 reverse of 432
关于c - 使用循环语句进行 C 练习 : Write code to reverse numbers with do-while statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64499670/