编程语言
首页 > 编程语言> > 编写程序输入实现123->321

编写程序输入实现123->321

作者:互联网

 #include<iostream>
 using namespacestd;
 int main(){
     int n;
     cin>>n;
     do{
         cout<<n%10;
     }while(n/=10)
     return 0;
 }

 

思路:这个方法使用了取余和取整的操作,能够实现对一个整型数据逆向输出处理。

 
#include<stdio.h>
 int main(){
     int n;
     scanf("%d",&n);
     //使用while()实现
     while(n!=0){
         printf("%d",n%10);
         n=n/10;
     }
     printf("\n");
     return 0;
 }
 #include<stdio.h>
 int main(){
     int n;
     scanf("%d",&n);
     //使用for()实现
     for(n;n!=0;n/10){
         printf("%d",n%10);
     }
     printf("\n");
     return 0;
 }

 

优化程序,提高运行速度

 
#include<stdio.h>
 int main(){
     int n,m;
     scanf("%d",&n);
     while(n!=0){
         m=m*10+n%10;
         n=n/10;
     }
     printf("%d\n",m);
 }

 

延伸1:如果输入的对象是一个整型数组,逆向输出。

 
#include<iostream>
 using namespace std;
 int main(){
     int a[100];
     int n;
     cin>>n;
     for(int i=0;i<n;i++)
     {
         cin>>a[i];
     }
     for(int j=n-1;j>=0;j--)
     {
         cout<<a[j]<<" ";
     }
     return 0;
 }

 

数组的长度:在c语言中,没有获取数组长度的函数。

字符串的长度:c语言中没有字符串,用的是字符串数组来模拟字符串。sizeof计算字符串在内存中的长度,即数组长度,返回的是变量声明后所占的内存数,不是实际长度;strlen计算的是字符串的有效长度(不包括'\0')

sizeof是运算符,strlen()是函数

标签:10,main,编写程序,int,123,printf,字符串,include,321
来源: https://www.cnblogs.com/181118ljh123/p/15077538.html