sony往年程序筆試真題

思而思學(xué)網(wǎng)

A、該題用語言描述是指:第i行第一個(gè)輸出,然后輸出i-1個(gè).,重復(fù)上i次。#include

#define N 8

int main()

{

int i;

int j;

int k;

for(i=0;i<=N;i++)

{

for(j=1;j<=i;j++)

{

printf("");

for(k=1;k

printf(".");

}

printf("n");

}

return 0;

B、降序排列數(shù)組,很常見的,這里我采用冒泡排序法還有選擇排序法:

冒泡排序:

#include

void sort(int array,int num );

int main()

{

int num=9,i;

int array[]={45,56,76,234,1,34,23,2,3};

sort(array,num);

for(i=0;i

printf("%dt",array);

return 0;

}

void sort(int array,int num)

{

int i,j;

int temp;

for(i=0;i

{

for(j=0;j

{

if(array[j]

{

temp=array[j];

array[j]=array[j+1];

array[j+1]=temp;

}

}

}

}

選擇排序:

#include

void sort(int array,int num );

int main()

{

int num=9,i;

int array[]={45,56,76,234,1,34,23,2,3};

sort(array,num);

for(i=0;i

printf("%dt",array);

return 0;

}

void sort(int array,int num)

{

int i,j,k;

int temp;

for(i=0;i

{

k=i; //每次一趟結(jié)束后就從新的一個(gè)值開始,無需從頭來,因?yàn)槊恳淮闻磐旰蠖际亲畲蟮牧?/p>

for(j=i+1;j

if(array[k]

{

k=j;

}

if(k!=i) //如果k不等于i就說明有更大的值,交換二值

{

temp=array;

array=array[k];

array[k]=temp;

}

}

}

C、該題考查同學(xué)們對遞歸算法的認(rèn)識程度,在這里我們采用迭代算法,優(yōu)點(diǎn)是程序運(yùn)行效率高,而且不用擔(dān)心堆棧溢出,在運(yùn)算值大的情況下比遞歸算法可以提高上萬倍的速度,比如同樣計(jì)算30,遞歸算法用時(shí)

0.019s,而迭代算法則只用了0.003s,可見是遞歸算法的八分之一,值更大時(shí)這種越明顯。缺點(diǎn)是程序比較不容易懂。有興趣的可以參見《C和指針》127頁,具體程序如下:

遞歸法:

#include

int Pheponatch(int);

int main()

{

printf("The 10th is %d",Pheponatch(30));

return 0;

}

int Pheponatch(int N)

{

if(N<=2)

return 1;

return Pheponatch(N-1)+Pheponatch(N-2);

}

迭代法:

#include

int Pheponatch(int);

int main()

{

printf("The 10th is %d",Pheponatch(30));

return 0;

}

int Pheponatch(int n)

{

long result;

long Pvious_result;

long next_older_result;

result=Pvious_result=1;

while(n>2)

{

n-=1;

next_older_result=Pvious_result+result;Pvious_result=result;

result=next_older_result;

}

return result;

}

D、源程序如下,紅筆寫出的是修改的地方:(其實(shí)這個(gè)程序有好多漏洞,不知為什么會(huì)那這個(gè)程序來考)

#include

#include

typedef struct{

TNode left;

TNode right;

int value;

} TNode;

TNode root=NULL;

void append(int N);

int main()

{

append(63);

append(45);

append(32);

append(77);

append(96);

append(21);

append(17); // Again, 數(shù)字任意給出

}

void append(int N)

{

TNode NewNode=(TNode )malloc(sizeof(TNode));

NewNode->value=N;

NewNode->right=NULL;

NewNode->left=NULL;

if(root==NULL)

{

root=NewNode;

return;

}

else

{

TNode temp;

temp=root;

while((N>=temp.value && temp.left!=NULL) || (N

right

!=NULL

))

{

while(N>=temp.value && temp.left!=NULL)

temp=temp.left;

while(N

temp=temp.right;

}

if(N>=temp.value)

temp.left=NewNode;

else

temp.right=NewNode;

return;

}

}

原因:因?yàn)樾鹿?jié)點(diǎn)的左右指針沒有賦 NULL 值,至使下面的 while循環(huán)不能正確結(jié)束而導(dǎo)致內(nèi)

存越界,最后崩潰(注意結(jié)束條件是 temp->left!= NULL 或 temp->right!=NULL)。

熱門推薦

最新文章