折半查找函数
#include<stdio.h>
int half_search(int arr[],int first,int last,int n)
{
int mid = 0;
while(first <= last)
{
mid = (first+last)/2;
if(n < arr[mid]) //若要查找的数字小于中间数,则在前一半查找
{
last = mid - 1; //范围缩小
}
else if(n > arr[mid]) //若大于中间数,在后一半查找
{
first = mid + 1;
}
else
return 1;
}
return -1;
}
int main()
{
int arr[] = {1,3,5,6,7,9,11,12,14,15}; //折半查找法适用于有序排列的数组
int i;
scanf("%d",&i);
if(half_search(arr,0,sizeof(arr)/sizeof(arr[0])-1,i) == -1)
{
printf("not exist\n");
}
else
{
printf("%d\n",i);
}
return 0;
}2.编写一个程序,它从标准输入读取C源代码,并验证所有的花括号都正确的成对出现。
#include<stdio.h>
int main()
{
int ch = 0;
int count = 0;
while ((ch = getchar()) != EOF)
{
if (ch == ‘{‘)
count++;
else if (ch == ‘}‘ && count == 0)
{
printf("匹配不成功\n");
system("pause");
return 0; //若匹配不成功,就无法再输入
}
else if (ch==‘}‘ && count != 0)
{
count--;
}
}
if (count == 0)
{
printf("匹配程序\n");
}
else
{
printf("匹配不成功\n");
}
system("pause");
return 0;
}上面是老师写的代码,如果将代码一次性拷贝到标准输入中,可以判断,但如果从键盘一个个敲进去代码,不匹配时返回值0,就无法继续输入了,我是这样写的
#include<stdio.h>
int main()
{
char c;
int i = 0,j = 0;
while((c = getchar()) != EOF)
{
if(c == ‘{‘)
{
i++;
}
else if(c == ‘}‘)
{
j++;
}
while(j > i)
{
if((c = getchar()) == EOF) //当右大括号出现且比左大括号多时,就一定不匹配了
goto flag; //此时就应该一直保持j>i的情况,不再累加
}
{
flag: if(i == j)
{
printf("花括号都配对正确\n");
}
else
printf("花括号未正确配对\n");
return 0;
}虽然用了一个goto语句,老师说最好不要用,但我觉得我的程序就比老师的通用性好啊,不管是拷贝还是输入,都可以在完成后一次性判断括号的匹配情况
3.编写一个程序,从标准输入读取几行输入。每行输入都要打印到标准输出上,前面加上行号。在编写这个程序的时候要使这个程序能够处理的输入行的长度没有限制。
#include <stdio.h>
int main()
{
int ch = 0;
int line = 1;
int flag = 1;
while ((ch = getchar()) != EOF)
{
if (flag) /*老师说这题的思路就是设计一个开关flag,当没有输入换行符时,开
{ 关打开,也就是输出一个行号,输完之后置成0关上,当输入换行符
printf("%d", line); 时再打开flag,输出行号*/
line++;
flag = 0;
}
if (ch == ‘\n‘)
flag = 1;
putchar(ch);
}
system("pause");
return 0;
}我当时想的太简单了,以为在输入的时候每行前面加上一个行号就好了
本文出自 “敲完代码好睡觉zzz” 博客,请务必保留此出处http://2627lounuo.blog.51cto.com/10696599/1698220
原文地址:http://2627lounuo.blog.51cto.com/10696599/1698220