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

标签 c loops while-loop do-while do-loops

我有一个任务(目前正在研究循环语句,所以我处于初学者阶段),要求编写一个程序来反转整数,因此它必须具有 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/

相关文章:

c - 使用 fscanf : Finding a char in an input

c - 对于 IMEI 号码和 MAC 地址的组合输入集,是否存在完美的哈希函数? (C实现)

Java for循环,初始化变量满足终止要求但循环没有终止

php - 多个帖子页面的 If 语句 - 显示/隐藏 - Wordpress

python - 在 python 循环中计算数字

PHP - 向我解释这个 while/for 循环

php - 可通过 TCP 访问守护进程以保持 SSH session 打开、创建新 session 和发送命令

c - R 中是否有比 readLines 更快的东西 - 或者我如何找出读取连接速度如此慢的原因?

无法输入 if 条件和函数返回段错误错误

Java:nextInt() 验证不起作用属性