c语言数字反转怎么做?

Python039

c语言数字反转怎么做?,第1张

代码有不懂的地方可以问,会回答的

#include<stdio.h>

#include<math.h>

int main( )

{

int N , temp , result = 0 

scanf( "%d" , &N ) 

temp = abs( N )   //取绝对值

while( temp % 10 == 0 && temp != 0 ) //先把末尾的0都去掉

temp /= 10 

do{

result = result * 10 + temp % 10  //加入个位

temp /= 10    //去掉个位

} while( temp != 0 ) 

if( N < 0 )    //如果是负数,结果也要为负数

result *= -1 

printf( "%d\n" , result ) 

return 0

}

#include <stdio.h>

#include <conio.h>

int main()

{

int former,latter=0

printf("请输入需要反转的整数:")

scanf("%d",&former)

do

{

latter*=10

latter+=former%10

former/=10

}

while (former)

printf("反转后整数为:%d",latter)

getch()

}二楼的方法是从低到高获取每一位数字逐个输出,而我的这种方法是计算出反转之后的数据,然后再输出。

用字符串处理很简单

#include <stdio.h>

#include <string.h>

void main ()

{

int n,i

char s[20]

scanf("%d", &n)

sprintf(s,"%d", n)

printf("%d\n",strlen(s))

for(i=strlen(s)-1i>=0i--){

printf("%c",s[i])

}

printf("\n")

}

如果要用循环也可以的。

补充:

#include<stdio.h>

void main()

{

long x

int temp=0,num=0

printf("请输入一个整数:\n")

scanf("%ld",&x)

printf("它的每一位数字是:\n")

while(x>0)

{

printf("%3d",x%10)

temp=temp*10+x%10

x=x/10

num++

}

printf("\n它是一个%d位数.\n",num)

printf("它的逆序是:%d\n",temp)

}