gpt4 book ai didi

c - 使用循环语句 : Write code to reverse numbers with do-while statement 用 C 语言练习

转载 作者:行者123 更新时间:2023-12-04 08:42:20 24 4
gpt4 key购买 nike

我有一个任务(目前正在研究循环语句,所以我处于初学者阶段)要求制作一个程序来反转整数,所以它必须有 do 语句。
输出应该是(示例):

Enter a number: 4568The 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 takeexample 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 = 43x = 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 = 4x = 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 - 使用循环语句 : Write code to reverse numbers with do-while statement 用 C 语言练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64499670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com