一、任意进制数转化为任意进制数
#include<stdio.h>
#include<math.h>
#include<string.h>
int toTenNumber(char *num,int len,int src){
int i,ten=0;
for (i =0; i<len;i++)
{ if(*(num +len-1- i)>='A'&&*(num+len-1 + i)<='Z')
ten += ((*(num+len-1 - i) % 65)+10) * pow(src,i);
else
ten += (*(num+len-1 - i)-48) * pow(src,i);
}
return ten;
}
int exchange(char *num,char *object,int size,int from,int to){
int i=0;
int tennumber = toTenNumber(num,size,from);
while(tennumber!=0){
if(tennumber%to>=10)
object[i] = tennumber % to + 55;
else
object[i] = tennumber % to + 48;
tennumber /= to;
i++;
}
return i - 1;
}
int main(){
char src[1024],object[1024];
int from,to;
scanf("%s %d %d",src,&from,&to);
int len=exchange(src,object,(int)strlen(src),from,to);
for (int i=0; i <= len;i++)
{
printf("%c",object[len-i]);
}
return 0;
}
二、打印n以内所有素数
#include<stdio.h>
int main(){
int n,i,j;
scanf("%d",&n);
if(n>=1)
printf("1 ");
for (i = 1; i <= n;i++)
{
for (j = 2; j < i;j++)
{
if(i%j==0)
break;
}
if(i==j)
printf("%d ",i);
}
return 0;
}
三、将结构体数据写入到文件中
#include<stdio.h>
#include<stdlib.h>
struct student
{
int id;
char name[10];
int age;
}stu;
int main(){
scanf("%d %s %d",&stu.id,stu.name,&stu.age);
FILE *fp;
if((fp = fopen("student.txt","w"))==NULL)
exit(-1);
fprintf(fp,"%d %s %d",stu.id,stu.name,stu.age);
fclose(fp);
return 0;
}
四、从文件中读取数据到结构体中
#include<stdio.h>
#include<stdlib.h>
struct student
{
int id;
char name[10];
int age;
}stu;
int main(){
FILE *fp;
if((fp = fopen("student.txt","r"))==NULL)
exit(-1);
fscanf(fp,"%d %s %d",&stu.id,stu.name,&stu.age);
fclose(fp);
printf("%d %s %d\n",stu.id,stu.name,stu.age);
return 0;
}
|