c语言编程练习(一)

/*
 *文件中有一组整数,要求排序后输出到另一个文件中
 *author:jxb
 *date:2015\4\3
 */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int num ;	
char c;
FILE *fd;
void get_data(int *scr,int *len)
{
	*len = 0;
	num = 0;
	
	fd = fopen("1.txt","r"); 	/*r该文件必须存在;w若文件不存在则建立该文件*/
	while((c=fgetc(fd))!=EOF)	/*当读到文件末尾或者读取出错时返回EOF*/
	{
		if((c>=48)&&(c<=57))
		{
			num = num*10+c-48;	/*字符转为十进制数*/
		}
		else
		{
			scr[(*len)++] = num;
			num = 0;
			while((c=fgetc(fd))!=EOF)	
			{
				if(!((c>=48)&&(c<=57)))	/*剔除非数字*/
					continue;
				else
				{
					num = num*10+c-48;
					break;
				}
			}
		}
	}
	if(num>0)
		scr[(*len)++] = num;
	fclose(fd);	
}

int compar(const void *a, const void *b)
{
	return *(int *)a - *(int *)b;	
}

void output(int *scr,int *len)
{
	int i;
	fd = fopen("2.txt","w");
	for(i=0;i<(*len);i++)
	{	
		fprintf(fd,"%d",*scr++);	
		fprintf(fd,"%c",' ');
	}
	fclose(fd);
}

void main()
{
	int j,len;
	int scr[100];
	get_data(scr,&len);
	qsort(scr,len,sizeof(int),compar);	/* 比较函数compar的作用就是给qsort指明 元素的大小是怎么比较的*/
	//printf("%d\n",len);			/*http://www.cnblogs.com/syxchina/archive/2010/07/29/2197382.html*/	
	//for(j=0;j<len;j++)
	//printf("%d\n",scr[j]);
	output(scr,&len);
	
}

/*总结:函数参数的传递最好用指针传递*/

<pre name="code" class="cpp">/*
 *查看一个字符中1的个数
 *author:jxb
 *date:2015\4\3
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
	char a;
	int string[8]={0,0,0,0,0,0,0,0};
	int j;
	printf("please input:\n");
	scanf("%c",&a);
	printf("%o\n",a);  /*该字符的8进制输出*/
	char b = a;
	for(j=7;b;j--)		/*二进制转换*/
	{
		string[j] = b%2;
		b = b >> 1;	
	}
	for(j=0;j<8;j++)
	{
	printf("%d",string[j]);
	}
	printf("\n");
	int i=0;
	while (a)		/*打印1的个数*/
	{
		i += a&1;
		a >>=1;
	
	}
	printf("%d\n",i);

}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值