【C/C++】C語言復習筆記-17種小算法-解決實際問題


判斷日期為一年中的第幾天(考慮閏年)

 1 /*
 2 * 計算該日在本年中是第幾天,注意閏年問題
 3 * 以3月5日為例,應該先把前兩個月的加起來,然后再加上5天即本年的第幾天
 4 * 特殊情況,閏年且輸入月份大於3時需考慮多加一天
 5 */
 6 
 7 /*
 8 *@author: 成鵬致遠 
 9 *@net: http://infodown.tap.cn
10 */
11 
12 #include <stdio.h>
13 #include <stdbool.h>
14 
15 struct year_mon_day
16 {
17     int year;
18     int mon;
19     int day;
20 };
21 
22 int main()
23 {
24     int i;
25     int sum;//總天數
26     bool flag = false;//閏年標志
27     struct year_mon_day ymd;
28     
29     printf("Pls input year,mon day:");
30     scanf("%d%d%d",&ymd.year,&ymd.mon,&ymd.day);
31     
32     switch(ymd.mon)
33     {
34         case 1:
35             sum = 0;
36             break;
37         case 2:
38             sum = 31;
39             break;
40         case 3:
41             sum = 59;
42             break;
43         case 4:
44             sum = 90;
45             break;
46         case 5:
47             sum = 120;
48             break;
49         case 6:
50             sum = 151;
51             break;
52         case 7:
53             sum = 181;
54             break;
55         case 8:
56             sum = 212;
57             break;
58         case 9:
59             sum = 243;
60             break;
61         case 10:
62             sum = 173;
63             break;
64         case 11:
65             sum = 304;
66             break;
67         case 12:
68             sum = 334;
69             break;
70         default:
71             printf("data error \n");
72             return 1;
73     }
74     sum += ymd.day;
75 
76     if(ymd.year/100 || (ymd.year%4 && ymd.year%100 != 0))
77     {
78         flag = true;
79     }
80     
81     if(1==flag && ymd.mon>2)
82     {
83         sum++;
84     }
85 
86     printf("%d年%d月%d日 是%d年的第%d天 \n",ymd.year,ymd.mon,ymd.day,ymd.year,sum);
87 
88     return 0;
89 }
View Code

十進制轉十六進制

 1 /*函數實現輸入一個十進制數,輸出對應的十六進制數*/
 2 /*
 3 *@author: 成鵬致遠 
 4 *@net: http://infodown.tap.cn
 5 */
 6 
 7 #include <stdio.h>
 8 #include <stdbool.h>
 9 #define LIM 32
10 
11 int main(void)
12 {
13     int decimal;
14     bool negative = false;
15     printf("pls input the integer to convert:\n");
16 
17     if(!scanf("%d", &decimal))
18     {
19         printf("we need an integer, Bye-bye!\n");
20         return -1;
21     }
22     if(decimal < 0)
23     {
24         negative = true; 
25         decimal *= -1;
26     }
27 
28     int i, num[LIM];
29     for(i=0; i<LIM && decimal!=0; i++)
30     {
31         num[i] = decimal%16;
32         decimal /= 16;
33     }
34 
35     int j;
36     if(negative)
37         printf("answer: -0x");
38     else
39         printf("answer: 0x");
40 
41     for(j=i; j>0; j--){
42         switch(num[j-1]){
43             case 10:
44                 printf("a");
45                 break;
46             case 11:
47                 printf("b");
48                 break;
49             case 12:
50                 printf("c");
51                 break;
52             case 13:
53                 printf("d");
54                 break;
55             case 14:
56                 printf("e");
57                 break;
58             case 15:
59                 printf("f");
60                 break;
61             default:
62                 printf("%d", num[j-1]);
63                 break;
64         } //switch
65     } //for
66     printf("\n");
67 
68     return 0;
69 }
View Code

打印指定的字母金字塔(技巧)

 1 /*
 2 *    產生一個字母金字塔圖案
 3 *    author:成鵬致遠
 4 *    net:infodown.tap.cn
 5 */
 6 
 7 #include <stdio.h>
 8 
 9 void PintLetterPic(char);    //打印出金字搭字母圖案
10 
11 int main()
12 {
13     char letter;
14 
15     printf("Please input a capital letter:");
16     scanf("%c",&letter);
17     
18     PintLetterPic(letter);
19 
20     return 0;
21 }
22 
23 void PintLetterPic(char c)    //打印出金字搭字母圖案
24 {
25     int len = c - 'A'+1;    //注意這里需要+1!!!
26     int len2 = 2*len;
27     char tem[100][200];
28     int i,j;
29     char tempchar = 'A';
30 
31     for(i=0; i<100; i++)    //初始化二維數組
32     {
33         for(j=0; j<200; j++)
34         {
35             tem[i][j] = ' ';
36         }
37     }
38 /*******************************核心算法*********************************************/    
39 
40     for(i=0; tempchar<=c; i++,tempchar++)//從最中間列從上往下控制行
41     {
42         int m = 1;
43         char temp = tempchar;    //需要保存tempchar的一個臨時變量,保證tempchar在while循環中不被改變
44         tem[i][len] = tempchar;    //控制最中間的一列
45 
46 
47         while('A' != temp)    //從行最中間左右控制列
48         {
49             tem[i][len-m]=tem[i][len+m]=--temp;
50             m++;
51         }
52     }
53 
54 /*******************************核心算法*********************************************/    
55 
56 
57     for(i=0; i<len; i++)    //打印出金字塔圖案
58     {
59         for(j=0; j<len2; j++)
60         {
61             printf("%c",tem[i][j]);
62         }
63         printf("\n");
64     }
65 }
View Code

求float型數的冪

 1 /*用循環的方法實現,返回一個float 類型數的某個整數次冪,保留六位小數*/
 2 /*
 3 *@author: 成鵬致遠 
 4 *@net: http://infodown.tap.cn
 5 */
 6 
 7 #include <stdio.h>
 8 #include <math.h>
 9 
10 float my_power(float cardinal, int pow);    //返回cardinal的pow次冪
11 
12 int main()
13 {
14     float cardinal;    //底數
15     int pow;    //
16 
17     printf("Please input a float cardinal and a int pow(3.14,-2):");
18     scanf("%f,%d",&cardinal,&pow);
19 
20     printf("%f的%d次冪是:%.6f \n",cardinal,pow,my_power(cardinal,pow));
21 
22     return 0;
23 }
24 
25 float my_power(float cardinal, int pow)
26 {
27     float result = 1.0;
28     int abs_pow = abs(pow);
29 
30     if(0 != abs_pow)    //非0次冪
31     {
32         while(abs_pow--)
33         {
34             result *= pow>0?cardinal:1/cardinal;
35         }    
36     }
37     else    //0次冪
38     {
39         result =1;
40     }
41     return result;
42 }
View Code

輸出小於指定數的所有素數

 1 /*
 2 *    接受一個整數輸入,然后顯示所有小於或等於該數的素數
 3 *    編譯時請加 -lm 選項,鏈接到 math 庫
 4 *    author:成鵬致遠
 5 *    net:infodown.tap.cn
 6 */
 7 
 8 #include <stdio.h>
 9 #include <stdbool.h>
10 #include <math.h>
11 
12 bool IsPrime(int a);//判斷是否為素數
13 void PoutPrime(int a);//輸出所有小於或等於該數的素數
14 
15 int main()
16 {
17     int nem;
18 
19     printf("Please input a number:");
20     scanf("%d",&nem);
21 
22     PoutPrime(nem);
23 
24     return 0;
25 }
26 
27 bool IsPrime(int a)//判斷是否為素數
28 {
29     int i;
30     int j = sqrt(a);
31 
32     for(i=2; i<=j; i++)
33     {
34         if(0 == a % i)
35         {
36             return false;
37         }
38     }
39     return true;
40 }
41 
42 void PoutPrime(int a)//輸出所有小於或等於該數的素數
43 {
44     printf("小於或等於%d 的所有素數列表:\t",a);
45     while(a)
46     {
47         if(IsPrime(a))
48         {
49             printf("%d\t",a);
50         }
51         a--;
52     }
53     printf("\n");
54 }
View Code

輾轉相除法求最大公約數(鋪磚)

 1 /*
 2 * 返回兩個整數的最大公約數,用輾轉相除法求最大公約數
 3 * 輾轉相除法:鋪地磚
 4 * author:成鵬致遠
 5 * net:infodown.tap.cn
 6 */
 7 
 8 #include <stdio.h>
 9 
10 int Divisor(int a, int b)    //最大公約數
11 {
12     int temp;
13 
14     if(a < b)
15     {
16         a = a ^ b;
17         b = a ^ b;
18         a = a ^ b;
19     }
20     while(0 != b)
21     {
22         temp = a % b;
23         a = b;
24         b = temp;
25     }
26     return a;    //最大公約數
27                 //最大公倍數為兩數的乘積除以最大公約數
28 }
29 
30 int main()
31 {
32     int a,b;
33 
34     printf("Please input two numbers:");
35     scanf("%d%d",&a,&b);
36 
37     printf("%d 和%d 的最大公約數是%d \n",a,b,Divisor(a,b));
38 }
View Code

遞歸實現漢諾塔(遞歸思想)

 1 /*
 2 * 遞歸實現漢諾塔
 3 * @author:成鵬致遠
 4 * @net:infodown.tap.cn
 5 */
 6 
 7 #include <stdio.h>
 8 
 9 void move(char a, char b)//實現漢諾塔的移動
10 {
11     printf("%c—>%c \n",a,b);
12 }
13 
14 
15 /*
16 * 功 能: 遞歸實現漢諾塔
17 * n    : 盤子個數
18 * a,b,c: 三個盤座
19 */
20 void han_tower(int n, char a, char b, char c)
21 {
22     if(1==n)
23     {
24         move(a,c);
25     }
26     else
27     {
28         //將前n-1個盤子從a借助c移動到b
29         han_tower(n-1,a,c,b);
30         //將a上的第n個盤子移動到c
31         move(a,c);
32         //將剩下的n-1個盤子從b借助a移動到c
33         han_tower(n-1,b,a,c);
34     }
35 }
36 
37 int main()
38 {
39     int num;
40 
41     printf("Pls input the number of diskes:");
42     scanf("%d",&num);
43     printf("the step to moving %d diskes: \n",num);
44     han_tower(num,'A','B','C');
45 
46     return 0;
47 }
View Code

乒乓球比賽對手配對(匹配)

 1 /*
 2 題目:兩個乒乓球隊進行比賽,各出三人。甲隊為a,b,c三人,乙隊為x,y,z三人。已抽簽決定
 3     比賽名單。有人向隊員打聽比賽的名單。a說他不和x比,c說他不和x,z比,請編程序找出
 4     三隊賽手的名單。 
 5 */
 6 
 7 /*
 8 *  @author: 成鵬致遠 
 9 *  @net: http://infodown.tap.cn
10 */
11 
12 #include <stdio.h>
13 
14 int main(void)
15 {
16     char i,j,k;
17     for(i='x';i<='z';i++)//a對手
18     {
19         for(j='x';j<='z';j++)//b對手
20         {
21             if(i!=j)//a,b同對
22             {
23                 for(k='x';k<='z';k++)//c對手
24                 { 
25                     if(i!=k&&j!=k)//a,b,c同對
26                     { 
27                         if(i!='x' && k!='x' && k!='z')//a不和x比,c不和x,z比
28                             printf("order is a--%c\tb--%c\tc--%c \n",i,j,k);
29                     }
30                 }
31             }
32         }
33     }
34     
35     return 0;
36 }
View Code

函數區間求最大值(方法)

 1 /*
 2 編程:設x取值為區間[1,20]的整數,求函數f(x)=x-sin(x)- cos(x)的最大值
 3 要求使用自定義函數實現f(x)功能
 4 */
 5 
 6 /*
 7 *  @author: 成鵬致遠 
 8 *  @net: http://infodown.tap.cn
 9 */
10 
11 #include "stdio.h"
12 #include "math.h"
13 double f()
14 {
15    int i;
16    double max=0,x;
17    for(i=1;i<=20;i++)
18    {
19      x=i-sin(i)-cos(i);
20      if(x-max>1e-6)
21        max=x;
22    }
23    return max;
24 
25 }
26 main()
27 {
28     printf("%lf",f());
29     getchar();
30 }
View Code

分解質因數

 1 /*
 2 題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。
 3 程序分析:對n進行分解質因數,應先找到一個最小的質數k,然后按下述步驟完成:
 4 (1)如果這個質數恰等於n,則說明分解質因數的過程已經結束,打印出即可。
 5 (2)如果n<>k,但n能被k整除,則應打印出k的值,並用n除以k的商,作為新的正整數你n,
 6   重復執行第一步。
 7 (3)如果n不能被k整除,則用k+1作為k的值,重復執行第一步。
 8 */
 9 
10 #include <stdio.h>
11 #include <math.h>
12 
13 main()
14 {
15     int n,i;
16     printf("please input a number:\n");
17     scanf("%d",&n);
18     printf("%d=",n);
19     for(i=2;i<=sqrt(n);i++)
20     {
21         while(n!=i)
22         {
23             if(n%i==0)
24             {
25                 printf("%d*",i);
26                 n=n/i;
27             }
28             else
29                 break;
30         }
31     }
32     printf("%d \n",n);
33 }
View Code

古代買雞問題

 1 /*
 2 編程解決如下問題:雞翁一,值錢五;雞母一,值錢三;雞雛三,值錢一。
 3 百錢買百雞,問雞翁,雞母,雞雛各幾何?
 4 
 5 解決方案:數學問題,先用數學方法解決
 6 1、設雞翁、雞母、雞雛分別a、b、c只
 7 2、5a+3b+c/3=100
 8 3、a+b+c=100
 9 4、解得:b=(100-7*a)/4;
10        c=(300+3*a)/4;
11 
12 */
13 
14 /*
15 *  @author: 成鵬致遠 
16 *  @net: http://infodown.tap.cn
17 */
18 
19 #include<stdio.h>
20 
21 void main()
22 {
23     int a,b,c;
24     for(a=0;a<20;a++)
25     {
26         b=(100-7*a)/4;
27         c=(300+3*a)/4;
28         if(a+b+c==100&&a>=0&&b>=0&&c>=0)
29         {
30                 printf("%d,%d,%d\n",a,b,c);
31         }
32     }
33 }
View Code

字符串交叉連接

 1 //輸入兩個字符串,要求將這兩個字符串交叉連接。如串1為"ABCD",串2為"123456",則合並后的串為"A1B2C3D456"。
 2 
 3 /*
 4 *  @author: 成鵬致遠 
 5 *  @net: http://infodown.tap.cn
 6 */
 7 
 8 #include<stdio.h>
 9 #include<stdlib.h>   
10 void main()
11 {
12     char a[20],s[20],*p1,*p2;
13     gets(a);
14     gets(s);
15     p1=a;
16     p2=s;
17     while(1)
18     {
19         if(*p1!='\0')
20         {    
21             printf("%c",*p1);p1++;
22         }
23         if(*p2!='\0')
24         {
25             printf("%c",*p2);
26             p2++;
27         }
28         if(*p1=='\0' && *p2=='\0')
29             exit(0);
30     }
31 }
View Code

完數

 1 /*
 2 題目:一個數如果恰好等於它的因子之和,這個數就稱為“完數”。例如6=1+2+3.編程
 3     找出1000以內的所有完數。
 4 */
 5 
 6 /*
 7 *  @author: 成鵬致遠 
 8 *  @net: http://infodown.tap.cn
 9 */
10 
11 #include <stdio.h>
12 
13 int main(void)
14 {
15     static int k[10];
16     int i,j,n,s;
17     for(j=2;j<1000;j++)
18     {
19         n=-1;
20         s=j;
21         for(i=1;i<=j/2;i++)
22         {
23             if((j%i)==0) //因子
24             {
25                 n++;
26                 s=s-i; //減到0則是完數
27                 k[n]=i;
28             }
29         }
30         if(s==0)
31         {
32             printf("%d 是一個完數 \n%d=",j,j);
33             for(i=0;i<n;i++)
34                 printf("%d+",k[i]);
35             printf("%d \n",k[n]);
36         }
37     }
38 
39     return 0;
40 }
View Code

容器分水移動(算法)

 1 /*
 2 編程解決如下數學問題:有12升水,怎樣利用一個8升
 3 和一個5升的容器將水分為兩個6升?要求以如下格式
 4 打印出分水步驟。
 5 a12  b8  c5
 6 12   0   0
 7 *    *   * ( “*”表示當前狀態下每個容器的盛水量)
 8 ......
 9 6   6   0
10 */
11 
12 /*
13 *  @author: 成鵬致遠 
14 *  @net: http://infodown.tap.cn
15 */
16 
17 #include <stdio.h>
18 
19 
20 void move(int *ai,int *aj,int aiContainer,int ajContainer) //將油從一個容器導倒入另外一個容器
21 {      //移動容器目前盛水量,接收容器目前盛水量,移動容器容量,接收容器容量
22 
23     if(aiContainer>ajContainer) //移動容器容量>接收容器容量
24     {
25         if(*ai+*aj>ajContainer) //將油倒入接收容器中,移動容器有剩余
26         {
27             *ai=*ai-(ajContainer-*aj);
28             *aj=*aj+ajContainer-*aj;
29         }
30         else //將油倒入接收容器中,移動容器無剩余
31         {
32             *aj=*ai+*aj; 
33             *ai=*ai-*ai;
34         }
35     }
36     else //移動容器容量<接收容器容量,則全部倒入接收容器中
37     {
38         *aj=*ai+*aj;
39         *ai=0;
40     }
41 }
42 
43 int main(void)
44 {
45     int a[3]={12,0,0},i,m=0;
46     int container[3]={12,8,5};
47     printf("%-8s%-8s%-8s\n","a12","b8","c5");
48     printf("%-8d%-8d%-8d\n",a[0],a[1],a[2]);
49     while(a[0]!=6)
50     {
51         for(i=0;i<3;i++)//循環三次,分別從a->b,b->c,c->a
52         {
53             move(&a[i],&a[(i+1)%3],container[i],container[(i+1)%3]);
54             m++;
55             printf("%-8d%-8d%-8d\n",a[0],a[1],a[2]);
56             if(a[0]==6 && a[1]==6)
57             {
58                 printf("The total number is %d to reach success!",m);
59                 getchar();
60                 return 0;
61             }
62         }
63         move(&a[1],&a[2],container[1],container[2]);//b->c
64         printf("%-8d%-8d%-8d\n",a[0],a[1],a[2]);
65         m++;
66         if(a[0]==6 && a[1]==6)
67         {
68             printf("The total number is %d to reach success!",m);
69             break;
70         }
71     }
72     getchar();
73     return 0;
74 }
View Code

猴子吃桃問題(逆向思維)

 1 /*
 2 猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不癮,又多吃了一個
 3     第二天早上又將剩下的桃子吃掉一半,又多吃了一個。以后每天早上都吃了前一天剩下
 4     的一半零一個。到第10天早上想再吃時,見只剩下一個桃子了。求第一天共摘了多少。
 5 1.程序分析:采取逆向思維的方法,從后往前推斷。
 6 */
 7 
 8 /*
 9 *  @author: 成鵬致遠 
10 *  @net: http://infodown.tap.cn
11 */
12 
13 #include <stdio.h>
14 
15 int main(void)
16 {
17     int day,x1,x2;
18     day=9;
19     x2=1;
20     while(day>0)
21     {
22         x1=(x2+1)*2;
23         x2=x1;
24         day--;
25     }
26     printf("the total is %d \n",x1);
27 
28     return 0;
29 }
View Code

統計字符數字等

 1 /*
 2 題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數
 3 */
 4 
 5 /*
 6 *  @author: 成鵬致遠 
 7 *  @net: http://infodown.tap.cn
 8 */
 9 
10 #include <stdio.h>
11 
12 int main(void)
13 {
14     char c;
15     int letters=0,space=0,digit=0,others=0;
16     printf("please input some characters: \n");
17     while((c=getchar())!='\n')
18     {
19         if(c>='a'&&c<='z'||c>='A'&&c<='Z')
20             letters++;
21         else if(c==' ')
22             space++;
23         else if(c>='0'&&c<='9')
24             digit++;
25         else
26             others++;
27     }
28     printf("all in all:char=%d space=%d digit=%d others=%d \n",letters,space,digit,others);
29 
30     return 0;
31 }
View Code

貪心算法用例(夠糾結的)

  1 /*
  2 編程解決如下問題。
  3   請在整數n=742683613984中刪除8個數字,使得余下的數字按原次序組成的新數最小。要求如下:
  4   (1)整數n和刪除數字的個數“8”在源程序中完成賦值,程序直接輸出運行結果;
  5   (2)程序結果輸出先后被刪除的數字(之間以逗號分隔)和刪除后所得的最小數。
  6   (提示:整數n可以以字符數組的方式定義、賦值和處理)
  7 
  8   編寫思路:
  9   在前9位數字中尋找最小數字a1,記下該最小數字的位置b1,a1前面所有數字是該刪除的,
 10   個數m=b1-1,然后從a1后面開始繼續操作,變為刪除8-m個數字,從a1后8-m+1個數字中找最小值a2,
 11   記下b2,刪除a1與a2之間的數字,個數b2-b1-1。m=m+b2-b1-1.如此下去直至m=8,停止操作,
 12   輸出a1a2……及最后一個a和之后的數字。
 13 
 14   程序一是正確的,程序二是錯誤的
 15   一和二的差別主要是在刪除字符序列的順序上
 16 */
 17 
 18 /*
 19 *  @author: 成鵬致遠 
 20 *  @net: http://infodown.tap.cn
 21 */
 22 
 23 //程序一:貪心算法
 24 
 25 #include <string.h>
 26 #include <stdio.h>
 27 
 28  int main()
 29 {
 30   int i,m=8,t=0;
 31   char p[10];
 32   char s[]="742683613984";
 33   for (i=0;i<12;i++)
 34   {
 35         while(t&&p[t-1]>s[i]&&m) //用p數組中的每一個元素和當前s[i]比較
 36         {
 37             t--,m--; //進入循環意味着s[i]比p[--t]小,需要將p[--t]輸出,並且m-1
 38             printf("%c",p[t]);
 39             if(m) //未刪除所有符合條件的元素之前,用逗號將各元素分開
 40             printf(",");
 41         }
 42         p[t++]=s[i]; //p數組依次暫存前一位比后一位小的數字
 43   } //循環結束后p數組中存儲着最小的四位數
 44         p[t]=0; //字符數組結束
 45         printf("\n");
 46         puts(p);
 47         return 0;
 48 }
 49         
 50           
 51  
 52 /*
 53 //程序二:這個是錯誤的,程序一和程序二的差別在刪除字符序列的順序
 54 
 55     #include <stdio.h>
 56     #include <stdlib.h>
 57     
 58      void main()
 59      {
 60          char *s="742683613984";
 61          printf("%s\n",s); 
 62          //去掉8個相當於取4個
 63          int a,b,c,d;//下標
 64          int aa,bb,cc,dd;//某位數字
 65          int ka,kb,kc,kd;//最小值對應的下標
 66          int min=10000;//當取4個時,設定初始最小值為5位數
 67          int num;//組和的值
 68          for(a=0;a<=8;a++)
 69          {
 70              for(b=1;b<=9;b++)
 71              {
 72                  for(c=2;c<=10;c++)
 73                  {
 74                      for(d=3;d<=11;d++)
 75                      {
 76                          if((a<b)  && (b<c) && (c<d)  )//保證不重復和先后順序
 77                          {
 78                              aa=s[a]-'0';bb=s[b]-'0';cc=s[c]-'0';dd=s[d]-'0';//字符型轉換為整數
 79                              num=aa*1000+bb*100+cc*10+dd;//求組和數
 80                              if (num<min)//選擇最小值以及下標
 81                              {
 82                                  min=num;
 83                                  ka=a;kb=b;kc=c;kd=d;//最小值對應的下標
 84                              }
 85                          }
 86                      }
 87                  }
 88              }
 89         }
 90      
 91      for(int i=0;i<=11;i++)//輸出去掉的數
 92      {
 93          if(i!=ka && i!=kb && i!=kc && i!=kd)
 94              printf("%c\t",s[i]); 
 95      }
 96      printf("\n%d\n",min);//輸出最小值 
 97      system("pause");
 98 }
 99 
100 
101 */
102   
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM