一些筆試的代碼

來源:互聯網
上載者:User

1、非遞迴求最小公倍數和最大公約數

#include<stdio.h>void main(){int a,b,num1,num2,temp;printf("please input num1 and num2 \n");scanf("%d%d",&num1,&num2);if(num1 > num2){a = num1;b = num2;}else{a = num2;b = num1;}while(b > 0){temp = a % b;a = b;b = temp;}printf("最大公約數是%d\n最小公倍數是%d\n",a,(num1 * num2) / a);}

2、遞迴求最大公約數

//用遞迴求最大公約數#include<stdio.h>int gcd(int m,int n);int main(){  int m,n; printf("Input m,n:\n");  scanf("%d%d",&m,&n);  printf("%d\n",gcd(m,n));}int gcd(int m,int n){ if(m>n)//大於和小於只要"<"或">"就夠了,不需要兩個  return gcd(m-n,n);  else if(m<n)  return gcd(m,n-m); else if(m==n)  return m;}

3、字串單詞倒置題

//字串轉置#include<string.h>#include<stdio.h>void Reversion(char *str)//方法一,利用string.h庫函數{    int n=strlen(str)-1;    //char *temp=(char*)malloc(n+1);    char temp[30]="";    while(n>0)    {        if((str[n]!=' ')&&(str[n-1]==' '))        {            strcat(temp,str+n-1);            str[n]='\0';        }        n--;    }    strcat(temp,str+n);    printf("%s\n",temp);}void turn(char *str)//方法二,利用迴圈{    char temp;    int j=strlen(str)-1,i=0,begin,end;    while(j>i)    {        temp=str[i];        str[i]=str[j];        str[j]=temp;        j--;        i++;    }    printf("%s\n",str);    i=0;    while(str[i])    {        if((str[i]!=' ')){begin=i;while(str[i]&&str[i]!=' ')i++;end=i-1;}while(end>begin){temp=str[begin];str[begin]=str[end];str[end]=temp;end--;begin++;}        i++;    }    printf("%s\n",str);}void main(){    char str[30]="hello world future";    Reversion(str);    char str1[]="ni hao a";    turn(str1);}

4、判斷低地址還是高地址優先

#include<stdlib.h>#include<stdio.h>void main(){    int a=10;    short b;    memcpy(&b,&a,2);//將a的低兩位元組賦值給b    printf("%d\n",b);}

5、字串翻轉

#include <stdio.h>#include <string.h>void rotate(char *start, char *end){    while(start != NULL && end !=NULL && start<end)    {        char temp=*start;        *start=*end;        *end=temp;        start++;        end--;    }}void leftrotate(char *p,int m){    if(p==NULL)        return ;    int len=strlen(p);    if(m>0&&m<=len)    {        char *xfirst,*xend;        char *yfirst,*yend;        xfirst=p;        xend=p+m-1;        yfirst=p+m;        yend=p+len-1;        rotate(xfirst,xend);        rotate(yfirst,yend);        rotate(p,p+len-1);    }}int main(void){    char str[]="abcdefghij";    leftrotate(str,3);    printf("%s\n",str);    return 0;}

6、判斷系統大端小端儲存

#include<stdio.h>union s{int i;char ch;}c;int check(){c.i=1;return (c.ch);}void main(){if (check()){printf("little\n");}elseprintf("big\n");}


7、一道求機率的問題即一個邊長為10的正方形和一個半徑為10的圓重疊的部分答案為25π左右

#include<stdio.h>#include<time.h>void main(){    int count=0,i=100;    srand(time(0));    while(i>0)    {        int a=rand()%10;        int b=rand()%10;        if((a*a+b*b)<=100)            count++;        i--;    }    printf("%d",count);}

8、數組a[N],存放了1至N-1個數,其中某個數重複一次,找出重複的那個數

#include<iostream>  using namespace std;  void do_dup(int a[] , int n)  {      int *b = new int[n];      for( int i = 0 ; i != n ; ++i )      {          b[i] = -1 ;      }      for( int j = 0 ; j != n ; ++j )      {          if( b[a[j]] == -1 ){              b[a[j]] = a[j] ;          }          else          {          cout << b[ a[j] ] << endl ;          break ;          }        }  }  int main(){      int a[]={  1 , 2 , 3 , 4 , 3 } ;      do_dup( a , 5 ) ;  }   

9、用兩個線程實現1-100的輸出

package lzf.thread;//用兩個線程實現1-100的輸出public class Synchronized {// state==1表示線程1開始列印,state==2表示線程2開始列印private static int state = 1;private static int num1 = 1;private static int num2 = 1;public static void main(String[] args) {final Synchronized t = new Synchronized();new Thread(new Runnable() {@Overridepublic void run() {while (num1 < 95){// 兩個線程都用t對象作為鎖,保證每個交替期間只有一個線程在列印synchronized (t) {// 如果state!=1, 說明此時尚未輪到線程1列印, 線程1將調用t的wait()方法, 直到下次被喚醒if (state != 1) {try {t.wait();} catch (InterruptedException e) {e.printStackTrace();}}// 當state=1時, 輪到線程1列印5次數字for (int j = 0; j < 5; j++) {System.out.println("num1:"+num1);num1 += 1;num2 = num1;}// 線程1列印完成後, 將state賦值為2, 表示接下來將輪到線程2列印state = 2;// notifyAll()方法喚醒在t上wait的線程2, 同時線程1將退出同步代碼塊, 釋放t鎖t.notifyAll();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (num2 < 100) {synchronized (t) {if (state != 2) {try {t.wait();} catch (InterruptedException e) {e.printStackTrace();}}for (int j = 0; j < 5; j++) {System.out.println("num2:"+num2);num2 += 1;num1 = num2;}state = 1;t.notifyAll();}}}}).start();}}

linux下線程樣本

gcc -o pthread_test pthread_test .c -lpthread

#include<stddef.h>#include<stdio.h>#include<unistd.h>#include"pthread.h"void reader_function(void);void writer_function(void);char buffer;int buffer_has_item=0;pthread_mutex_t mutex;main(){    pthread_t reader;    pthread_mutex_init(&mutex,NULL);    pthread_create(&reader,NULL,(void*)&reader_function,NULL);    writer_function();}void writer_function(void){    while(1)    {        pthread_mutex_lock(&mutex);        if(buffer_has_item==0)        {    buffer='a';            printf("make a new item\n");            buffer_has_item=1;        }        pthread_mutex_unlock(&mutex);    }}void reader_function(void){    while(1)    {        pthread_mutex_lock(&mutex);        if(buffer_has_item==1)        {    buffer='\0';            printf("consume  item\n");            buffer_has_item=0;        }        pthread_mutex_unlock(&mutex);    }}

線程類比火車售票

package lzf.thread;class TicketSystem {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubSellThread st = new SellThread();new Thread(st).start();try{Thread.sleep(10);}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}new Thread(st).start();st.b = true;}}class SellThread implements Runnable{int tickets = 100;Object obj = new Object();boolean b = false;@Overridepublic void run() {// TODO Auto-generated method stubif(b==false){while(true){sell();}}while (true) {synchronized (this) {if(tickets>0){try{Thread.sleep(1);}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}System.out.println("obj"+Thread.currentThread().getName()+" sell tickets:"+tickets);tickets--;}}}}public synchronized void sell(){if(tickets>0){try{Thread.sleep(10);}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}System.out.println("sell"+Thread.currentThread().getName()+" sell tickets:"+tickets);tickets--;}}}

10、宏定義交換兩個數字

//第一種#define SWAP(x,y) ((x)=(x)+(y),(y)=(x)-(y),(x)=(x)-(y))//第二種#define SWAP(x,y) ((x)=(x)^(y),(y)=(x)^(y),(x)=(x)^(y))//比上一種更好,不會出現大數位溢出問題#define swap(x, y)///帶有換行x = x + y;/y = x - y;/x = x - y;#define swap(x, y)/x ^= y;/y ^= x;/x ^= y;void main(){int x=3,y=4;swap(x,y);printf("%d,%d",x,y);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.