小程序帮你很好的理解C语言
第三部分:编程题
1、读文件file1.txt的内容(例如):
12
34
56
输出到file2.txt:
56
34
12
#include
#include
int main(void)
{
int MAX = 10;
int *a = (int *)malloc(MAX * sizeof(int));
int *b;
FILE *fp1;
FILE *fp2;
fp1 = fopen(“a.txt”,”r”);
if(fp1 == NULL)
{printf(“error1″);
exit(-1);
}
fp2 = fopen(“b.txt”,”w”);
if(fp2 == NULL)
{printf(“error2″);
exit(-1);
}
int i = 0;
int j = 0;
while(fscanf(fp1,”%d”,&a[i]) != EOF)
{
i++;
j++;
if(i >= MAX)
{
MAX = 2 * MAX;
b = (int*)realloc(a,MAX * sizeof(int));
if(b == NULL)
{
printf(“error3″);
exit(-1);
}
a = b;
}
}
for(;–j >= 0;)
fprintf(fp2,”%d\n”,a[j]);
fclose(fp1);
fclose(fp2);
return 0;
}
2、输出和为一个给定整数的所有组合
例如n=5
5=1+4;5=2+3(相加的数不能重复)
则输出
1,4;2,3。
#include
int main(void)
{
unsigned long int i,j,k;
printf(“please input the number\n”);
scanf(“%d”,&i);
if( i % 2 == 0)
j = i / 2;
else
j = i / 2 + 1;
printf(“The result is \n”);
for(k = 0; k < j; k++)
printf("%d = %d + %d\n",i,k,i - k);
return 0;
}
#include
void main()
{
unsigned long int a,i=1;
scanf(“%d”,&a);
if(a%2==0)
{
for(i=1;i printf("%d",a,a-i);
}
else
for(i=1;i<=a/2;i++)
printf(" %d, %d",i,a-i);
}
3、递规反向输出字符串的例子,可谓是反序的经典例程.
void inverse(char *p)
{
if( *p = = '\0' )
return;
inverse( p+1 );
printf( "%c", *p );
}
int main(int argc, char *argv[])
{
inverse("abc\0");
return 0;
}
对1的另一种做法:
#include
void test(FILE *fread, FILE *fwrite)
{
char buf[1024] = {0};
if (!fgets(buf, sizeof(buf), fread))
return;
test( fread, fwrite );
fputs(buf, fwrite);
}
int main(int argc, char *argv[])
{
FILE *fr = NULL;
FILE *fw = NULL;
fr = fopen(“data”, “rb”);
fw = fopen(“dataout”, “wb”);
test(fr, fw);
fclose(fr);
fclose(fw);
return 0;
}
4、写一段程序,找出数组中第k大小的数,输出数所在的位置。例如{2,4,3,4,7}中,第一大的数是7,位置在4。第二大、第三大的数都是4,位置在1、3随便输出哪一个均可。函数接口为:int find_orderk(const int* narry,const int n,const int k)
要求算法复杂度不能是O(n^2)
谢谢!
可以先用快速排序进行排序,其中用另外一个进行地址查找
代码如下,在VC++6.0运行通过。给分吧^-^
//快速排序
#include
usingnamespacestd;
intPartition (int*L,intlow,int high)
{
inttemp = L[low];
intpt = L[low];
while (low < high)
{
while (low < high && L[high] >= pt)
–high;
L[low] = L[high];
while (low < high && L[low] <= pt)
++low;
L[low] = temp;
}
L[low] = temp;
returnlow;
}
voidQSort (int*L,intlow,int high)
{
if (low < high)
{
intpl = Partition (L,low,high);
QSort (L,low,pl - 1);
QSort (L,pl + 1,high);
}
}
intmain ()
{
intnarry[100],