Description
输入一个整型数,判断是否是对称数,如果是,输出yes,否则输出no,不用考虑这个整型数过大,int类型存不下,不用考虑负值
方法一 取余乘位权
#include <stdio.h>
int main() {int n,a,b=0,tmp;scanf("%d",&a);n=a;while (a){tmp = a%10;b=b*10+tmp;a=a/10;}if (n==b){printf("yes");} else{printf("no");}return 0;
}
方法二 转为字符串 sprintf + strlen + strcmp
#include <stdio.h>
#include "string.h"
int main() {int a;scanf("%d", &a);char string1[16] = {0},string2[16]={0};sprintf(string1,"%d",a); //整数a转换为字符串存入string1int len = strlen(string1);for(int i;i<len;i++){string2[len-i-1]=string1[i];}if (strcmp(string1,string2)==0){printf("yes");} else{printf("no");}return 0;
}
sprintf + malloc + perror + free的应用
#include"stdio.h"
#include"malloc.h"
int main(void) {char *a = NULL;//声明一个指向a的char*类型的指针a = (char *) malloc(100 * sizeof(char));//malloc将内存首地址赋值给a,失败返回nullif (!a){perror("oops:");return -1;}sprintf(a, "%s", "HelloWorld\n"); //"HelloWorld\n"写入a指向的地址printf("%s\n", a);free(a);//容易忘记!return 0;
}
sprintf 将多个数字写入字符串
int a,b;
scanf("%d %d",&a,&b);
char str[20]={0};
sprintf(str,"%d , %d",a,b); //将 a,b按“ ”中类型存入目标字符串地址str
printf("%s",str);