Menu Close

给出一个整数,然后用相反顺序打印出来 (递归函数, While 的应用)

1.利用递归函数
2.使用while loop

1.利用递归函数

#include<stdio.h>
   int main(){
   int num,reverse_number;

    //User would input the number
   printf("\nEnter any number:");
   scanf("%d",&num);

   //Calling user defined function to perform reverse
   reverse_number=reverse_function(num);
   printf("\nAfter reverse the no is :%d",reverse_number);
   return 0;
}
   int sum=0,rem;
   reverse_function(int num){
     if(num){
     rem=num%10;
     sum=sum*10+rem;
    reverse_function(num/10);
   }
   else
   return sum;
   return sum;
}

结果

Enter any number: 23456
After reverse the no is :65432

2.利用 while loop

#include<stdio.h>
int main()
{
   int num,rem,reverse_num=0;
   //Input number
   printf("\nEnter any number:");
   scanf("%d",&num);

   while(num>=1)
   {
   rem = num % 10;
   reverse_num = reverse_num * 10 + rem;
   num = num / 10;
   }

   printf("\nReverse of input number is: %d", reverse_num);
   return 0;
}

结果:


Enter any number:123456789

Reverse of input number is: 987654321

 

READ  C语言练习,利用条件语句计算一个整数的阶乘
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C语言习题集

Related Posts