C語言(C&C++程序設計基礎, 電子科技大學MOOC)


一、編程作業
1、在屏幕上輸出“hello! welcome to computer world!”

提示:

  1. 注意所有符號都是英文,最后沒有回車。

  2. 將要求輸出字符串之外的所有printf或者cout的輸出全部刪除

  3. 將return 0;之前的getchar();或者system("pause");等暫停程序運行的輸出都刪除。

  4. 提交之前先在自己的開發環境下運行成功再拷貝到作業區提交。

  5. 輸出的語句最好拷貝到程序中,避免不小心的鍵盤按鍵錯誤輸入造成扣分。

1 #include <stdio.h>
2 
3 int main()
4 {
5     printf("hello! welcome to computer world!");
6     return 0;
7 }

2、多行打印

打印下面的3行數據:

Please display these words:

1. press return keyboard to enter the game.

2. press esc keyboard to exist the game.

  1. 注意所有符號都是英文,最后沒有回車。

  2. 將要求輸出字符串之外的所有printf或者cout的輸出全部刪除

  3. 將return 0;之前的getchar();或者system("pause");等暫停程序運行的輸出都刪除。

  4. 提交之前先在自己的開發環境下運行成功再拷貝到作業區提交。

  5. 輸出的語句最好拷貝到程序中,避免不小心的鍵盤按鍵錯誤輸入造成扣分。

  6. 1.和2.后面有一個空格。

1 #include <stdio.h>
2 
3 int main()
4 {
5     printf("Please display these words:\n\
6 1. press return keyboard to enter the game.\n\
7 2. press esc keyboard to exist the game.");
8     return 0;
9 }
3、明星捐款

某明星每年都會做慈善,小明統計了一下這個明星今年做了3次慈善,第一次捐助希望小學x萬元,第二次捐助一個癌症患者y萬元,第三次舉辦了慈善晚會,募捐z萬元,其中有t萬元是其他人捐助的。

請問,這個明星今年一共捐助了多少錢?(萬元)

輸入: 4個空格分開的正實數(單精度實數)

輸出:總共捐款數(只輸出數值,保留小數點后的小數2位)

如果輸入不合法,則輸出error

例如:

輸入:3.2 5 7 5.5

輸出:10.50

輸入:5 -2 1 3

輸出:error

輸入:3 a 2 1

輸出:error

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     float x,y,z,t;
 6     int ret = scanf("%f%f%f%f",&x,&y,&z,&t);
 7     if(ret != 4 || x<=0 || y<=0 || z<=0 || t<=0)
 8         printf("error");
 9     else
10         printf("%.2f", x+y+z-t);
11     return 0;
12 }

4、發工資

小明每個月基本工資x元,還有獎金y元,每遲到1次扣獎金的50元。這個月遲到z次,最多將所有獎金扣完。

請問小明這個月領多少錢?

輸入:3個正整數

輸出:1個整數

如果輸入不合法,則輸出"error"

比如:

輸入:3000 200 2

輸出:  3100

輸入:5600 500 3

輸出:5950

輸入:1000 -2 5

輸出:error

輸入: 2000 200 6

輸出:2000

輸入:8000 200 -3

輸出: error

 1 #include <stdio.h>
 2 int main()
 3 {
 4     int x,y,z,t;
 5     int ret = scanf("%d%d%d",&x,&y,&z);
 6     
 7     if(ret != 3 || x<=0 || y<=0 || z<=0){
 8         printf("error");
 9     }
10     else{    
11         t = y-z*50;
12         if( t<0 ) t = 0;
13         printf("%d", x+t);
14     } 
15     return 0;
16 }

5、閏年判斷

題目內容:

輸入一個1900-2200之間的年份,

判斷這一年是不是閏年,是閏年輸出yes,不是則輸出no

閏年判斷條件:

1、能整除4且不能整除100 

2、能整除400

如果輸入不合法,輸出error

輸入樣例:

1900

輸出樣例:

no

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int y;
 6     int ret = scanf("%d",&y);
 7     if(ret != 1 || y<1900 && y>2200)
 8         printf("error");
 9     else if(y%4==0&&y%100!=0||y%400==0)
10         printf("yes");
11     else
12         printf("no");
13     return 0;
14 }

6、百錢百雞

題目內容:

一只公雞值5錢,

一只母雞值3錢,

三只小雞值1錢,

現在用百錢買百雞,

請問公雞、母雞、小雞各多少只?

列舉所有可能,從公雞數目小到大排列,公雞相同則按照母雞遞增順序,公雞母雞都相同,則按照小雞遞增順序

輸出結果:

a,b,c

d,e,f

.....

(a,d...對應公雞數量,b,e...對應母雞數量,c,f...對應小雞數量)

 1 #include <stdio.h> 
 2 int main()
 3 {
 4     int i,j,k;
 5     for(i=0; i<=100/5; ++i){
 6         for(j=0; j<=100/3; ++j){
 7             k = 100 - i - j; //百雞 
 8             if(k%3==0 && 100 == k/3 + i*5 + j*3) //百錢 
 9                 printf("%d,%d,%d\n",i,j,k);
10         }
11     }
12     return 0;
13 }

7、猴子摘桃

題目內容:

一個猴子摘了些桃子,

第一天吃掉其中的一半然后多吃了1個,

第二天照此方法又吃掉了剩下桃子的一半加1個,

以后每天如此,直到第十天晚上,猴子發現只剩下了1個桃子,

請問猴子第一天總共摘了多少個桃子?

並反向打印每天所剩桃子數。

即a,b,c,d.....,sum

分別表示第九天剩余桃子,第八天剩余桃子,....,第一天剩余桃子,總桃子數。

比如,如果總桃子10個,第一天剩余10/2-1=4個,第二天剩余4/2-1=1個,根據題目要求應該輸出第一天剩余桃子,總桃子分別為:

4,10

 1 #include <stdio.h> 
 2 int main()
 3 {
 4     int day = 10, remain = 1;
 5     for(day =10; day>0; --day)
 6     {
 7         remain = 2 * (remain + 1);
 8         if(day!=10)
 9             printf(",");
10         printf("%d", remain);
11     }
12     return 0;
13 }

8、回文判斷

題目內容:

回文測試:輸入一30個字符以內的字符串,判斷是否為回文;如果是,則打印"true";否則打印"false"。像"aba"這樣的從左往右讀與從右往左讀一致就是回文。

輸入樣例1:

ayzya

輸出樣例1:

true

輸入樣例2:

ayzy

輸出樣例2:

false

 1 #include <stdio.h> 
 2 #include <string.h>
 3 int main()
 4 {
 5     char str[31] = "";
 6     scanf("%s",str);
 7     char *p1=str, *p2 = str+strlen(str)-1;
 8     while(p1<p2 && *p1==*p2){
 9         p1++,p2--;        
10     }
11     if(p1>=p2)
12         printf("true");
13     else
14         printf("false");
15     return 0;
16 }

9、設計數字時鍾

題目內容:

按照下面要求定義一個時鍾結構體類型:

struct clock

{

    int hour;

    int minute;

    int second;

};

typedef struct clock CLOCK;

然后,編程實現將時鍾模擬顯示在屏幕上。注意:時鍾是24小時的。需要判斷輸入的數據是否合法。

輸入樣例1:

10,20,3

輸出樣例1:

10:20:03

輸入樣例1:

25,100,200

輸出樣例2:

error

 1 #include <stdio.h> 
 2 #include <string.h>
 3 
 4 struct clock
 5 {
 6     int hour;
 7     int minute;
 8     int second;
 9 };
10 typedef struct clock CLOCK;
11 
12 int main()
13 {
14     CLOCK c;
15     int ret = scanf("%d,%d,%d",&c.hour,&c.minute,&c.second);
16     if(ret!=3 || c.hour>=24 || c.minute>=60 || c.second>=60){
17         printf("error");
18     }
19     else{
20         printf("%02d:%02d:%02d",c.hour,c.minute,c.second);
21     }
22     return 0;
23 }

10、排序

題目內容:

接受若干非負整數(數據不重復),當個數超過10個或者遇到負數時停止接受,將這幾個整數按升序排列輸出,並且奇數在前,偶數在后。

輸出要求,每個數字后輸出空格與其他數字隔開,最后一個數字后也有空格

輸入樣例1:

10 9 8 7 6 5 4 3 2 1

輸出樣例1:

1 3 5 7 9 2 4 6 8 10回車

輸入樣例2:

2 3 4 5 -1

輸出樣例2:

3 5 2 4回車

 

 1 #include <stdio.h> 
 2 #include <string.h>
 3 
 4 void InsertSort(int *arr, int n)
 5 {
 6     int i;
 7     for(i=1; i<n; ++i){/*第0個元素有序,從第1個元素向右無序*/
 8         int j=i-1,key=arr[i];/*保存第i個元素,左邊的元素i-1*/
 9         while(j>=0 && key<arr[j]){/*保存的元素key與之前的元素從右向左逐個比較*/
10             arr[j+1]=arr[j];/*移動(向后賦值)*/
11             j--;
12         }
13         arr[j+1]=key;/*j--退出,恢復正確值j+1*/
14     }
15 }
16 
17 int main()
18 {
19     int i=0,x,flag=0, arr[10]={0};
20 
21     scanf("%d",&x);
22     while(i<10 && x>0){                
23         arr[i++] = x;
24         scanf("%d",&x);        
25     }
26     
27     InsertSort(arr,i);
28     for(int j=0; j<i; ++j){
29         if(arr[j]%2){
30             if(flag) printf(" ");
31             flag = 1;
32             printf("%d",arr[j]);
33         }
34     }
35         
36     for(int j=0; j<i; ++j){
37         if(arr[j]%2==0)
38             printf(" %d",arr[j]);
39     }
40        
41     return 0;
42 }

11、最大整數

題目內容:

輸入3個整數a,b,c,用指針p=&a,q=&b,請用max指向最大整數並輸出。

輸出按照如下格式輸出: printf("max=%d\n",*pmax);

輸入樣例:

1,2,3 

輸出樣例:

max=3

 1 #include <stdio.h>
 2 int main()
 3 {
 4     int a,b,c,max;
 5     int *pmax = &max;
 6     scanf("%d,%d,%d",&a,&b,&c);
 7     
 8     if(a>b)
 9         max = a;
10     else
11         max = b;
12     if(c>max)
13         max = c;
14     printf("max=%d\n",*pmax);
15     return 0;
16 }

12、刪除字符串中連續的重復字符

題目內容:

功能:實現刪除字符串中連續的重復字符(除字母和數字)。 輸入為字符串,將字符串中連續重復的,非字母和數字的字符刪去,然后輸出處理后的字符串。要求用指針指向輸入的字符串進行操作。

輸入格式:

輸入字符串最長50個字符,之后截斷,只輸出處理后的字符串。 

輸出格式:

輸入樣例:

1+++2==3

輸出樣例: 

1+2=3

 1 #include <stdio.h>
 2 #define N 100
 3 int main()
 4 {
 5     char str[N] = "";
 6     char *p = str;
 7     gets(str);
 8     
 9     while(*p){    
10         printf("%c",*p++);
11         while(*p&&!(*p>='0'&&*p<='9'||*p>='a'&&*p<='z'||*p>='A'&&*p<='Z')&&*p==*(p-1))
12                 p++;    
13     }
14     printf("\n");
15     return 0;
16 }

13、統計輸出字符串中的字母個數和數字個數。

題目內容:

編寫程序,輸入一個字符串,分別統計輸出該字符串中的字母個數和數字個數。要求用指針指向這個字符串進行處理。

輸入格式:

字符串

輸出格式:

英文逗號分隔的2個整數,第一個整數是字母個數,第二個整數的數字個數。

輸入樣例:

the day the month the year 123 

輸出樣例:

21,3

 1 #include <stdio.h>
 2 #define N 100
 3 int main()
 4 {
 5     char str[N] = "";
 6     char *p = str;
 7     int letters = 0, digits = 0;
 8     gets(str);
 9         
10     while(*p){
11         if(*p>='0'&&*p<='9')
12             digits++;
13         if(*p>='a'&&*p<='z'||*p>='A'&&*p<='Z')
14             letters++;
15         p++;
16     }
17     printf("%d,%d\n",letters,digits);
18 
19     return 0;
20 }

14、比較字符串是否相等(25分)

題目內容:

編寫程序,輸入兩個字符串,通過2個指針p和q分別指向這2個字符串,比較字符串是否相等。 要求不使用strcmp函數。

輸入格式:

string1回車string2回車 

string1和string2最長為256,可能包含空格 

輸出格式:

相等輸出: equal

不等輸出: unequal

輸入樣例:

string1

string2

輸出樣例:

unequal

 1 #include <stdio.h>
 2 #define N 300
 3 int main()
 4 {
 5     char str1[N] = "";
 6     char str2[N] = "";
 7     char *p = str1, *q = str2;
 8     
 9     gets(str1);
10     gets(str2);
11         
12     while(*p&&*q&&*p==*q){
13         p++; q++;
14     }
15     
16     if(!(*p)&&!(*q))
17         printf("equal\n");
18     else
19         printf("unequal\n");
20 
21     return 0;
22 }

15、水仙花數

設有一個3位數,它的百位數、十位數、個位數的立方和正好等於這個3位數,如153=1+125+27。

編寫函數,返回小於等於傳入參數n且滿足該條件的三位數(稱為水仙花數)的個數。

(指定函數原型:int find(int n))

 返回值要求:如果傳入參數n不是三位數或者在該范圍內沒有找到,則find返回0,

                    否則返回找到的水仙花數的個數。

 注意:不要在find函數中打印(如調用printf或puts等函數)任何數據,否則視為錯誤。

提交的程序需要包含需要的頭文件及如下的main函數:

#include<stdio.h>

#include<stdlib.h>

int find(int n);

int main()

{

   int n,r;

  r=scanf("%d",&n);

  if(r!=-1){printf("error",return -1;}

  r=find(n);

  printf("%d",r);

  return 0;

}

輸入1:

  400

輸出1:

  3

輸入2:

  59

輸出2:

 0

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 int find(int n);
 5 int main()
 6 {
 7     int n,r;
 8     r=scanf("%d",&n);
 9     if(r!=1){printf("error"); return 0;}
10     r=find(n);
11     printf("%d",r);
12     return 0;
13 }
14 int find(int n){
15     int cnt = 0;
16     if(n>=100&&n<=999)
17     for(int i = 123; i<=n; ++i ){
18         int a = i%10, b = i/10%10, c = i/100;
19         if(a*a*a + b*b*b + c*c*c == i) cnt++;
20     }
21     return cnt;
22 }

16、最小公倍數

編寫程序,從鍵盤輸入5個正整數,然后求出它們的最小公倍數,並顯示輸出。

(通過調用對兩個正整數求最小公倍數的函數實現)(參考函數原型:int LCM(int x, int y))

輸入輸出格式要求:

 編寫函數int LCM(int x, int y);返回值為x和y的最小公倍數。

 要求在main函數接收5個正整數,然后通過調用LCM函數最終得到這5個數的最小公倍數,最后輸出最小公倍數。

如果輸入數據錯誤,輸出"error"。

例如:

輸入:2 3 6 9 10

輸出:90

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 int LCM(int x, int y);
 5 int GCD(int x, int y);
 6 int main()
 7 {
 8     /* */
 9     int a,b,c,d,e,ret;
10     ret = scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
11     if(ret!=5 || a<=0 || b<=0 || c<=0 || d<=0 || e<=0)
12         printf("error"); 
13         else 
14         printf("%d",LCM(LCM(LCM(LCM(a,b),c),d),e));
15     return 0;
16 }
17 
18 int LCM(int x, int y){
19     return x/GCD(x,y)*y; 
20 }
21 int GCD(int x, int y){
22     return y == 0 ? x : GCD(y, x%y); 
23 }

17、字符串的拷貝

編程實現函數:void my_strcpy(char * destination,char * source);

函數功能:將source指向的字符串拷貝到destination指向的位置。

注意:使用空格字符來表示字符串的結束。例如source指向位置,依次保存了字符'a',字符'b',字符空格' ',字符'c',則source指向的字符串為"ab"。destionation原來存儲的字符串是"xyz tdk",則拷貝后,destionation存儲的應該是“ab  tdk”。遇到異常情況,輸出"error";否則不要隨意輸出,會視為錯誤.

您的main函數需要讀入2個長度不超過80字節的字符串(按行及下面順序讀入source和destionation字符串),然后調用my_strcpy函數,最后用puts函數輸出destionation里面存儲的字符串。

例如:

輸入1:

xyz abc

a kp

輸出1:

xyz

輸入2:

xyz abc

a kppp

輸出2:

xyz pp

 1 #include<stdio.h>
 2  
 3 void my_strcpy(char * destination,char * source);
 4 int main()
 5 {
 6     char source[81] = "";
 7     char destination[81]="";
 8     gets(source);
 9     gets(destination);
10      
11     my_strcpy(destination,source);  
12     puts(destination);
13      
14     return 0;
15 }
16 void my_strcpy(char * destination,char * source){
17     if(destination == NULL||source ==NULL||source[0] ==' '){
18         printf("error");
19         return;
20     }
21     char *p1 = destination, *p2 = source;
22     while((*p1++ = *p2++) != ' ');
23 }

18、完成point類

定義一個點類Point,並定義成員函數double Distance(const & Point) 求兩點的距離。

輸入兩個點的坐標,創建兩個點, 然后調用Point類的Distance方法輸出兩個點的距離。

在你的代碼中除了實現Point類以外,還需一如下main函數:

int main(){

    double a,b,c,d;

   cin>>a>>b>>c>>d;

   Point A(a,b),B(c,d);

   cout<<A.Distance(B)<<endl;

   return 0;

}

如輸入:

1 2 3 4回車

輸出:

2.83

 1 #include <iostream>
 2 #include <iomanip>
 3 #include <cmath>
 4 using namespace std;
 5 class Point{
 6     double a,b;
 7 public:
 8     Point(double a, double b){
 9         this->a = a;
10         this->b = b;
11     }
12     double Distance(const Point &p){
13         return sqrt((a-p.a)*(a-p.a)+(b-p.b)*(b-p.b));
14     }
15 };
16 //
17 int main()
18 {
19     double a,b,c,d;
20     cin>>a>>b>>c>>d;
21     
22     Point A(a,b),B(c,d);
23     cout<<setprecision(3)<<A.Distance(B)<<endl;
24     return 0;
25 }

19、實現Usr類

實現User類的構造函數和AddUser方法添加新用戶,

實現int login(char *name,char * pass)方法,該方法接受用戶名和密碼,

判斷用戶名對應的密碼是否正確,如果正確返回用戶的編號,如果不正確返回-1。

User類的使用示意如下所示,在你的代碼中除了實現User類以外,還需一如下main函數

int main(){

 char name[10],name1[10],pass[10],pass1[10];

 cin>>name>>pass>>name1>>pass1;

 User user("LiWei","liwei101");

 user.AddUser(name,pass);

 if (user.login(name1,pass1) >=0)

 {

  cout<<"Success Login!"<<endl;

 }

 else{

  cout<<"Login failed!"<<endl;

 }

   return 0;

}

例如輸入:

test 1234567 test 123456回車

輸出:

Login failed!

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 #define N 100
 5 class User{
 6     string name[N];
 7     string pass[N];
 8     static int index;
 9 public:
10     User(string name,string pass){        
11         this->name[index] = name;
12         this->pass[index] = pass;
13         index++;
14     }
15     ~User(){index--;}
16     void AddUser(string name,string pass){
17         this->name[index] = name;
18         this->pass[index] = pass;
19         index++;
20     }
21     int login(string name,string pass){
22         for(int i=0;  i<=index; ++i)
23             if(this->name[i] == name && this->pass[i] == pass)
24                 return 1;
25         return -1;
26     }
27 };
28 int User::index = 0;
29 /* class User{
30     string name;
31     string pass;
32 public:
33     User(string name,string pass){
34         this->name = name;
35         this->pass = pass;
36     }
37     void AddUser(string name,string pass){
38         this->name = name;
39         this->pass = pass;
40     }
41     int login(string name,string pass){
42         if(this->name == name && this->pass == pass)
43             return 1;
44         return -1;
45     }
46 }; */
47 
48 int main()
49 {
50     char name[10],name1[10],pass[10],pass1[10];
51     cin>>name>>pass>>name1>>pass1;
52 
53     User user("LiWei","liwei101");
54 
55     user.AddUser(name,pass);
56 
57     if (user.login(name1,pass1) >=0)
58     {
59         cout<<"Success Login!"<<endl;
60     }
61     else{
62         cout<<"Login failed!"<<endl;
63     }
64     return 0;
65 }

20、實現Sutdent類

設計一個學生類Student,包含學生學號(最長10位)、姓名(不用支持中文最長12位)、三門課程成績(成績是單精度實數類型)等基本信息,

計算每門課程學生的平均成績。

需實現Student的display成員函數,依次輸出學號 姓名 和三門課的成績,每個輸出以空格隔開

成員函數 average1 ,average2 ,average3 ,分別返回三門課的平均成績。

Student類的使用方法如下所示,在你的代碼中除了實現Student類,還需引入以下代碼:

int main(){

 Student *stu1,*stu2,*stu3;

 char name1[10],name2[10],name3[10];

 char num1[12],num2[12],num3[12];

 int grade1[3],grade2[3],grade3[3];

 cin>>name1>>num1>>grade1[0]>>grade1[1]>>grade1[2];

 cin>>name2>>num2>>grade2[0]>>grade2[1]>>grade2[2];

 cin>>name3>>num3>>grade3[0]>>grade3[1]>>grade3[2];

 stu1 = new Student(name1,num1,grade1[0],grade1[1],grade1[2]);

 stu2 = new Student(name2,num2,grade2[0],grade2[1],grade2[2]);

 stu3 = new Student(name3,num3,grade3[0],grade3[1],grade3[2]);

 stu1->display();

 stu2->display();

 stu3->display();

  cout<<"The average grade of course1:"<<setprecision(4)<<stu2->average1()<<endl;

  cout<<"The average grade of course2:"<<setprecision(4)<<stu2->average2()<<endl;

  cout<<"The average grade of course3:"<<setprecision(4)<<stu2->average3()<<endl;

   return 0;

}

上述代碼執行時

輸入:

200906294 LiWeiwei 88 75 91 200902164 ChenHanfu 86 78 93 200908079 ZhanGaolin 94 69 97

輸出:

200906294 LiWeiwei 88 75 91回車

200902164 ChenHanfu 86 78 93回車

200908079 ZhanGaolin 94 69 97回車

The average grade of course1:89.33回車

The average grade of course2:67.33回車

The average grade of course3:93.67回車

 1 #include <iostream>
 2 #include <iomanip>
 3 #include <cmath>
 4 using namespace std;
 5 class Student{
 6     string name, num;
 7     float grade1,grade2,grade3;
 8     static float ave1,ave2,ave3;
 9     static int count;
10 public:
11     Student(string name,string num, float grade1,float grade2,float grade3){
12         this->name = name;
13         this->num = num;
14         this->grade1 = grade1;
15         this->grade2 = grade2;
16         this->grade3 = grade3;
17         count++;
18         ave1 += grade1;
19         ave2 += grade2;
20         ave3 += grade3;
21     }
22     void display(){
23         cout<<name<<" "<<num<<" "<<grade1<<" "<<grade2<<" "<<grade3<<endl;        
24     }
25     float average1(){
26         return ave1 /= count;
27     }    
28     float average2(){
29         return ave2 /= count;
30     }
31     float average3(){
32         return ave3 /= count;
33     }
34 };
35 float Student::ave1 = 0.0;
36 float Student::ave2 = 0.0;
37 float Student::ave3 = 0.0;
38 int Student::count = 0;
39 
40 int main()
41 {
42     Student *stu1,*stu2,*stu3;
43     char name1[10],name2[10],name3[10];
44     char num1[12],num2[12],num3[12];
45     int grade1[3],grade2[3],grade3[3];
46 
47     cin>>name1>>num1>>grade1[0]>>grade1[1]>>grade1[2];
48     cin>>name2>>num2>>grade2[0]>>grade2[1]>>grade2[2];
49     cin>>name3>>num3>>grade3[0]>>grade3[1]>>grade3[2];
50     
51     stu1 = new Student(name1,num1,grade1[0],grade1[1],grade1[2]);
52     stu2 = new Student(name2,num2,grade2[0],grade2[1],grade2[2]);
53     stu3 = new Student(name3,num3,grade3[0],grade3[1],grade3[2]);
54 
55     stu1->display();
56     stu2->display();
57     stu3->display();
58 
59      cout<<"The average grade of course1:"<<setprecision(4)<<stu2->average1()<<endl;
60     /**/cout<<"The average grade of course2:"<<setprecision(4)<<stu2->average2()<<endl;
61     cout<<"The average grade of course3:"<<setprecision(4)<<stu2->average3()<<endl; 
62     return 0;
63 }

21、形狀類

已知基類ShapeFactory的聲明如下:

const float pi=3.1416;

class ShapeFactory

{

public:

 ShapeFactory(){};

 virtual ~ShapeFactory(){};

 

 virtual float Circumstance(){return 0;};

}

  ShapeFactory *Create(float a,float b,float c);

  ShapeFactory *Create(float a,float b,float c,float d);

  ShapeFactory *Create(float r);

請寫出三角形(Triangle)、四邊形(Quadrangle)、圓形(Circle)三個派生類,構造函數分別傳入三邊/四邊/半徑的長度(不用檢查是否符合三角形、矩形、圓的條件,沒有異常輸出),重寫出求周長的函數(Circumstance函數)。

然后實現基類的Create函數,這里重載的三個Create函數,分別生成三角形、四邊形、圓形的對象。

比如三角形類為Triangle:

ShapeFactory * ShapeFactory::Create(float a,float b,float c)

{

 ShapeFactory *p=new Triangle(a,b,c);

 return p;

}

如果三角形輸入的三邊長度是 3 4 5,四邊形輸入的四條邊的長度是2 3 4 7,圓的半徑是3,則要求程序運行能夠得到如下的提示和輸出:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const float pi=3.1416;
 5 class ShapeFactory
 6 {
 7 public:
 8     ShapeFactory(){};
 9     virtual ~ShapeFactory(){};
10     virtual float Circumstance(){return 0;};
11 };
12 
13 class Triangle:public ShapeFactory
14 {
15     float a,b,c;
16 public:
17     Triangle(float a,float b,float c){
18         this->a = a;
19         this->b = b;
20         this->c = c;
21     }    
22     float Circumstance(){
23         return a+b+c;
24     }
25 };
26 
27 class Quadrangle:public ShapeFactory
28 {
29     float a,b,c,d;
30 public:
31     Quadrangle(float a,float b,float c,float d){
32         this->a = a;
33         this->b = b;
34         this->c = c;
35         this->d = d;
36     }
37     float Circumstance(){
38         return a+b+c+d;
39     }
40 };
41 
42 class Circle:public ShapeFactory
43 {
44     float r;
45 public:
46     Circle(float r){
47         this->r = r;
48     }
49     float Circumstance(){
50         return 2*pi*r;
51     }
52     
53 };
54 int main()
55 {
56     float a,b,c,d,r;
57     cout<<"輸入三角形的3邊長度:";
58     cin>>a>>b>>c;
59     Triangle t(a,b,c);
60     cout<<"三角形的周長為:"<<t.Circumstance()<<endl;
61     
62     cout<<"輸入四邊形的4邊長度:";
63     cin>>a>>b>>c>>d;
64     Quadrangle q(a,b,c,d);
65     cout<<"四邊形的周長為:"<<q.Circumstance()<<endl;
66     
67     cout<<"輸入圓的半徑:";
68     cin>>r;
69     Circle ci(r);
70     cout<<"圓的周長為:"<<ci.Circumstance()<<endl;
71         
72     return 0;
73 }

22、實現帶日期的時鍾類

實現帶日期的時鍾類,具體要求如下:

已知時鍾類的定義如下:

#include<iostream>

using namespace std;

bool leap(int year)

{

       if(year%400==0||(year%4==0 && year%100!=0))

              return true;

       return false;

}

class Clock{

public:

 Clock(int h,int m,int s)

 {

  hour =(h>23? 0:h);

  minute = (m>59?0:m);

  second = (s>59?0:s);

 }

 virtual void run()

 {

  second = second+1;

  if (second>59)

  {

   second =0;

   minute+=1;

  }

  if (minute>59)

  {

   minute =0;

   hour+=1;

  }

  if (hour>23)

  {

   hour =0;

  }

 }

 virtual void showTime()

 {

  cout<<"Now:"<<hour<<":"<<minute<<":"<<second<<endl;

 }

 int getHour(){return hour;}

 int getMinute(){return minute;}

 int getSecond(){return second;}

protected:

 int hour;

 int minute;

 int second;

};

日期類定義如下:

class Date{

public:

 Date(int y=1996,int m=1,int d=1)

 {

  if (m>12||m<1)

  {

   m=1;

  }

  if(d>days(y,m))

  {

   day = 1;

  }

  day =d;

  year =y;

  month =m;

 };

 int days(int year,int month);

 void NewDay();

 void showTime()

 {

  cout<<year<<"-"<<month<<"-"<<day<<endl;

 }

protected:

 int year;

 int month;

 int day;

};

int main()

{

       int h,m,s,day,month,year;

       cin>>h>>m>>s>>day>>month>>year;

       ClockWithDate cd1(h,m,s,day,month,year);

       cd1.showTime();

       cout<<"現在運行x秒:";

       int x;

       cin>>x;

       for(int i=0;i<x;++i)

              cd1.run();

       cd1.showTime();

       return 0;

}

需要類外實現Date類的days方法,根據年和月,返回該年該月對應的天數

實現Date類的NewDay方法,該方法將Date代表的日期增加一天。

實現ClockWithDate類,它繼承至Clock類和Date類,記錄時間和日期

重新實現ClockWithDate類的showTime方法和run方法。

showTime方法輸出當的時間和日期,先輸出時間再輸出日期。

run方法每次將現在的時間增加一秒,並且當時間超過23:59:59時,更新日期。

比如某次程序運行輸入當前時間是:1 1 1 7 10 2000(2000年10月7號1點1分1秒),然后輸入運行時間x: 5,則程序運行的輸入輸出如下:

輸入:

1 1 1 7 10 2000

5

輸出:

Now:1:1:1

2000-10-7

現在運行x秒:Now:1:1:6

2000-10-7

  1 #include<iostream>
  2 using namespace std;
  3 
  4 bool leap(int year)
  5 {
  6    if(year%400==0||(year%4==0 && year%100!=0))
  7       return true;
  8    return false;
  9 }
 10 
 11 class Clock
 12 {
 13 public:
 14     Clock(int h,int m,int s)
 15     {
 16         hour =(h>23? 0:h);
 17         minute = (m>59?0:m);
 18         second = (s>59?0:s);
 19     }
 20     virtual void run()
 21     {
 22         second = second+1;
 23         if (second>59)
 24         {
 25             second =0;
 26             minute+=1;
 27         }
 28         if (minute>59)
 29         {
 30             minute =0;
 31             hour+=1;
 32         }
 33         if (hour>23)
 34         {
 35             hour =0;
 36         }
 37     }
 38 
 39     virtual void showTime()
 40     {
 41         cout<<"Now:"<<hour<<":"<<minute<<":"<<second<<endl;
 42     }
 43     int getHour(){return hour;}
 44     int getMinute(){return minute;}
 45     int getSecond(){return second;}
 46 
 47 private:
 48     int hour;
 49     int minute;
 50     int second;
 51 };
 52 
 53 class Date
 54 {
 55 public:
 56     Date(int y=1996,int m=1,int d=1)
 57     {
 58         if (m>12||m<1)
 59         {
 60             m=1;
 61         }
 62         if(d>days(y,m))
 63         {
 64             day = 1;
 65         }
 66         day =d;
 67         year =y;
 68         month =m;
 69     };
 70 
 71     int days(int year,int month){        
 72         int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
 73         int d = days[month];
 74         if(leap(year)&&month==2)
 75             d++;        
 76         return d;
 77     }
 78     void NewDay(){
 79         day++;
 80         if(day>days(year,month))
 81         {
 82             day = 1;
 83             month++;
 84         }
 85         if(month>12){
 86             month = 1;
 87             year++;
 88         } /* */
 89     };
 90     void showTime()
 91     {
 92         cout<<year<<"-"<<month<<"-"<<day<<endl;
 93     }
 94 private:
 95     int year;
 96     int month;
 97     int day;
 98 };
 99 
100 class ClockWithDate:public Clock,Date
101 {
102 public:    
103     ClockWithDate(int h,int m,int s,int day,int month,int year):Clock(h,m,s),Date(year,month,day){}
104     void showTime()
105     {
106         Clock::showTime();
107         Date::showTime();
108     }
109     virtual void run()
110     {            
111         if(getSecond()==59&&getMinute()==59&&getHour()==23){
112             NewDay();
113         }
114         Clock::run();        
115     }
116 };
117 
118 int main()
119 {
120     int h,m,s,day,month,year;
121     cin>>h>>m>>s>>day>>month>>year;
122     ClockWithDate cd1(h,m,s,day,month,year);
123     cd1.showTime();
124     cout<<"現在運行x秒:";
125 
126     int x;
127     cin>>x;
128     for(int i=0;i<x;++i)
129           cd1.run();
130     cd1.showTime();
131     return 0;
132 }
二、考試題
1、編寫函數輸出小於等於n的水仙花數
設有一個3位數,它的百位數、十位數、個位數的立方和正好等於這個3位數,如153=1+125+27。
編寫函數,找出所有滿足該條件的數(稱為水仙花數)。
(參考函數原型:int find(int n))
輸入輸出格式要求:
	編寫函數int find(int n);
	在find里輸出所有小於等於n的水仙花數,以逗號分隔
	返回值要求:如果沒有,則find返回0,否則返回找到的水仙花數的個數
例如:
n為:400
輸出:153,370,371
find函數返回3
 1 # include <stdio.h>
 2 int find(int n)
 3 {
 4     int flag=0;
 5     for(int i=100; i<=n; ++i)
 6     {
 7         int a=i%10;
 8         int b = i/10%10;
 9         int c = i/100;
10         if(a*a*a+b*b*b+c*c*c==i)
11         {
12             if(flag)
13                 printf(",");
14             printf("%d",i);
15             flag++;
16         }            
17     }
18     printf("\n");
19     return flag;
20 }
21 int main()
22 {
23     int n;
24     scanf("%d",&n);
25     printf("%d\n",find(n));
26     return 0;    
27 }

2、逆序memcpy

實現逆序的Memcpy方法。
void * reversememcpy ( void * destination, const void * source, int num );
從source所指的內存地址的起始位置開始拷貝num個字節,逆序保存到目標destination所指的內存地址的起始位置中。
返回destination。

注意為逆序拷貝。source指向位置,依次保存了10,20,30,當num=3時,則逆序拷貝后destination指向的位置應該依次保存30,20,10.

輸入:1,2,3

輸出:3,2,1

(逆序拷貝,實參指針類型與函數指針類型必須一致,否則只能正序拷貝)

 1 # include <stdio.h>
 2 #define N 100
 3 void * reversememcpy ( void * destination, const void * source, int num );
 4 int main()
 5 {
 6     int arr[N] = {0},num = 3; 
 7     scanf("%d,%d,%d",&arr[0],&arr[1],&arr[2]);
 8     
 9     int *p = (int *)reversememcpy(&arr[num],&arr[0],num);
10     for(int i=0; i<num;++i)
11     {
12         if(i)
13             printf(",");
14         printf("%d",p[i]);
15     }        
16     return 0;    
17 }
18 void *reversememcpy(void *destination,const void *source,int num)
19 {
20     int *des=(int*)destination,*src=(int*)source;
21     des += num-1;
22     while(num--)
23     {
24         *des-- = *src++;  
25     }
26     return destination;
27 }

memcpy源碼(源頭目標內存重疊或目標內存不重疊(前后之分),從源頭開始復制;源尾目標內存重疊,從源尾開始復制)

 1 void *memcpy(void *dst, const void *src, size_t len)
 2 {
 3     if(NULL == dst || NULL == src){
 4         return NULL;
 5     }
 6     
 7     void *ret = dst;
 8     
 9     if(dst <= src || (char *)dst >= (char *)src + len){
10         //目標低於等於源或目標高於等於源+len,從源頭地址開始復制
11         while(len--){
12             *(char *)dst = *(char *)src;
13             dst = (char *)dst + 1;
14             src = (char *)src + 1;
15         }
16     }else{
17         //目標高於源並且小於源+len,從源尾地址開始復制
18         src = (char *)src + len - 1;
19         dst = (char *)dst + len - 1;
20         while(len--){
21             *(char *)dst = *(char *)src;
22             dst = (char *)dst - 1;
23             src = (char *)src - 1;
24         }
25     }
26     return ret;
27 }

3、擴展String類

首先輸入一個字符串,然后依次將功能顯示出來

輸入:testtesttest,3,test,t,a,test,str,t,es

輸出:4,aesaaesaaesa,strstrstr,eseses,tttttt

  1 #include <iostream>
  2 #include <cstring>
  3 #define N 256
  4 using namespace std;
  5 class String
  6 {
  7 protected:
  8     char *mystr;
  9     int len;
 10 public:
 11     String(const char *p)
 12     {
 13         len = strlen(p);
 14         mystr = new char[len+1];
 15         strcpy(mystr,p);
 16     }
 17     ~String()
 18     {
 19         if (mystr !=NULL)
 20         {
 21             delete []mystr;
 22             mystr = NULL;
 23             len = 0;
 24         }
 25     }
 26     void showStr(){cout <<mystr;}
 27     char * GetStr(){return mystr;}
 28     virtual bool IsSubString(const char *str)
 29     {
 30         int i,j;
 31         for (i =0;i<len;i++)
 32         {
 33             int k = i;
 34             for (j =0;str[j] !='\0';j++,k++)
 35             {
 36                 if (str[j]!= mystr[k]) break;
 37             }
 38             if(str[j] =='\0') return true;
 39         }
 40         return false;
 41     }
 42 };
 43 
 44 class EditString:public String{
 45 public:
 46     EditString(const char *p):String(p){}
 47     int IsSubString(int start, const char *str);
 48     void EditChar(char s, char d); 
 49     void EditSub(const char * subs,const char *subd); 
 50     void DeleteChar(char ch);  
 51     void DeleteSub(const char * sub);  /* */
 52 
 53 };
 54 int EditString::IsSubString(int start, const char *str)
 55 {
 56     int i=start,j;
 57     for (i =start;i<len;i++)
 58     {
 59         int k = i;
 60         for (j =0;str[j] !='\0';j++,k++)
 61         {
 62             if (str[j]!= mystr[k]) break;
 63         }
 64         if(str[j] =='\0') return i;
 65     }
 66     return -1;
 67 }
 68 void EditString::EditChar(char s, char d)
 69 {
 70     char *p = mystr;
 71     while(*p)
 72     {
 73         if(*p==s)
 74             *p = d;
 75         p++;
 76     }
 77 }
 78 void EditString::EditSub(const char * subs,const char *subd)
 79 {
 80     int start=0;
 81     char *temp = new char[len+1];
 82     while(start<len)
 83     {
 84         start=IsSubString(start,subs);
 85         if(start!=-1){
 86             strncpy(temp,mystr,start);
 87             temp[start] = '\0';
 88             strcat(strcat(temp,subd),&mystr[start+strlen(subs)]);
 89             strcpy(mystr,temp);
 90         }
 91         else{
 92             break;
 93         }
 94         start++;    
 95     }
 96     delete []temp;
 97     len = strlen(mystr);
 98 }
 99 void EditString::DeleteChar(char ch)
100 {
101     char *p = mystr,*q=mystr;
102     while(*q)
103     {
104         if(*q!=ch){
105             *p = *q;
106             p++;
107         }
108         q++;
109     }
110     *p = '\0';
111     len = strlen(mystr);
112 }
113 void EditString::DeleteSub(const char * sub){
114     int start=0;
115     char *temp = new char[len+1];
116     while(start<len)
117     {
118         start=IsSubString(start,sub);
119         if(start!=-1){
120             strncpy(temp,mystr,start);
121             temp[start] = '\0';
122             strcat(temp,&mystr[start+strlen(sub)]);
123             strcpy(mystr,temp);
124         }
125         else{
126             break;
127         }
128         start++;    
129     }
130     delete []temp;
131     len = strlen(mystr);
132 }
133 int main()
134 {
135     //testtesttest,3,test,t,a,test,str,t,es
136     char s[N],s1[N],s2[N],s3[N],s4[N],s5[N];
137     char c1,c2,c3;
138     int count;
139     cin>>s;
140     /* 1.實現int IsSubString(int start, const char *str); */
141     //---------------------s1,count,s2
142     char* p = strtok (s," ,.-");
143     strcpy(s1,p);
144     p = strtok (NULL," ,.-");
145     count = atoi(p);    
146     p = strtok (NULL," ,.-");
147     strcpy(s2,p);
148     EditString es1(s1);
149     cout<<es1.IsSubString(count,s2)<<",";//4
150     /* 2.實現EditChar(char s, char d)*/
151     //---------------------s1,c1,c2
152     p = strtok (NULL," ,.-");
153     c1 = *p;
154     p = strtok (NULL," ,.-");
155     c2 = *p;
156     EditString es2(s1);
157     es2.EditChar(c1,c2);
158     es2.showStr();  //"aesaaesaaesa"
159     cout<<",";
160     /* 3.實現void EditSub(char * subs,char *subd)*/ 
161     //---------------------s3,s4    
162     p = strtok (NULL," ,.-");
163     strcpy(s3,p);
164     p = strtok (NULL," ,.-");
165     strcpy(s4,p);
166     EditString es3(s1);
167     es3.EditSub(s3,s4);
168     es3.showStr();//"strstrstr"
169     cout<<",";
170     /* 4.實現void DeleteChar(char ch) */
171     //---------------------c3
172     p = strtok (NULL," ,.-");
173     c3 = *p;
174     EditString es4(s1);
175     es4.DeleteChar(c3);
176     es4.showStr();//"eseses"
177     cout<<",";
178     /* 5.實現void DeleteSub(char * sub)*/ 
179     //--------------s5
180     p = strtok (NULL," ,.-");
181     strcpy(s5,p);
182     EditString es5(s1);
183     es5.DeleteSub(s5);//"tttttt";
184     es5.showStr();
185     cout<<endl;
186     return 0;
187 }
 1 int main()
 2 {   //testtesttest,3,test,t,a,test,str,t,es
 3     char s[N]="";
 4     gets(s);
 5     EditString str(s);
 6     str.EditChar(',',' ');
 7     strcpy(s,str.GetStr());
 8     char s1[N]="",s2[N]="",s3[N]="",s4[N]="",s5[N]="";
 9     char c1,c2,c3;
10     int count;
11     sscanf(s,"%s%d%s %c %c%s%s %c%s",s1,&count,s2,&c1,&c2,s3,s4,&c3,s5);
12     /* 1.實現int IsSubString(int start, const char *str); */
13     //---------------------s1,count,s2
14     EditString es1(s1);
15     cout<<es1.IsSubString(count,s2)<<",";//4
16     /* 2.實現EditChar(char s, char d)*/
17     //---------------------s1,c1,c2
18     EditString es2(s1);
19     es2.EditChar(c1,c2);
20     es2.showStr();  //"aesaaesaaesa"
21     cout<<",";
22     /* 3.實現void EditSub(char * subs,char *subd)*/ 
23     //---------------------s3,s4    
24     EditString es3(s1);
25     es3.EditSub(s3,s4);
26     es3.showStr();//"strstrstr"
27     cout<<",";
28     /* 4.實現void DeleteChar(char ch) */
29     //---------------------c3
30     EditString es4(s1);
31     es4.DeleteChar(c3);
32     es4.showStr();//"eseses"
33     cout<<",";
34     /* 5.實現void DeleteSub(char * sub)*/ 
35     //--------------s5
36     EditString es5(s1);
37     es5.DeleteSub(s5);//"tttttt";
38     es5.showStr();
39     cout<<endl;
40     return 0;
41 }
  1 #include <iostream>
  2 #include <cstring>
  3 using namespace std;
  4 class String{
  5 protected:
  6     char *mystr;
  7     int len;
  8 public:
  9     String(const char *p){
 10         len = strlen(p);
 11         mystr = new char[len+1];
 12         strcpy(mystr,p);
 13     }
 14     ~String(){
 15         if (mystr !=NULL)
 16         {
 17             delete []mystr;
 18             mystr = NULL;
 19             len = 0;
 20         }
 21     }
 22     void showStr(){cout <<mystr;}
 23     char * GetStr(){return mystr;}
 24     virtual bool IsSubString(const char *str){
 25         int i,j;
 26         for (i =0;i<len;i++)
 27         {
 28             int k = i;
 29             for (j =0;str[j] !='\0';j++,k++)
 30             {
 31                 if (str[j]!= mystr[k]) break;
 32             }
 33             if(str[j] =='\0') return true;
 34         }
 35         return false;
 36     }
 37 };
 38 
 39 class EditString:public String{
 40 public:
 41     EditString(const char *p):String(p){}
 42     int IsSubString(int start, const char *str);
 43     void EditChar(char s, char d); 
 44     void EditSub(char * subs,char *subd); 
 45 
 46     void DeleteChar(char ch);  
 47     void DeleteSub(char * sub); 
 48 
 49 };
 50 int EditString::IsSubString(int start, const char *str)
 51 {
 52     int i=start,j;
 53     for (i =start;i<len;i++)
 54     {
 55         int k = i;
 56         for (j =0;str[j] !='\0';j++,k++)
 57         {
 58             if (str[j]!= mystr[k]) break;
 59         }
 60         if(str[j] =='\0') return i;
 61     }
 62     return -1;
 63 }
 64 void EditString::EditChar(char s, char d)
 65 {
 66     char *p = mystr;
 67     while(*p)
 68     {
 69         if(*p==s)
 70             *p = d;
 71         p++;
 72     }
 73 }
 74 void EditString::EditSub(char * subs,char *subd)
 75 {
 76     int start=0;
 77     char *temp = new char[len+1];
 78     while(start<len)
 79     {
 80         start=IsSubString(start,subs);
 81         if(start!=-1){
 82             strncpy(temp,mystr,start);
 83             temp[start] = '\0';
 84             strcat(strcat(temp,subd),&mystr[start+strlen(subs)]);
 85             strcpy(mystr,temp);
 86             len = strlen(mystr);
 87         }
 88         else{
 89             break;
 90         }
 91     }
 92     delete []temp;
 93 }
 94 void EditString::DeleteChar(char ch)
 95 {
 96     char *p = mystr,*q=mystr;
 97     while(*q)
 98     {
 99         if(*q!=ch){
100             *p = *q;
101             p++;
102         }
103         q++;
104     }
105     *p = '\0';
106     len = strlen(mystr);
107 }
108 void EditString::DeleteSub(char * sub){
109     int start=0;
110     char *temp = new char[len+1];
111     while(start<len)
112     {
113         start=IsSubString(start,sub);
114         if(start!=-1){
115             strncpy(temp,mystr,start);
116             temp[start] = '\0';
117             strcat(temp,&mystr[start+strlen(sub)]);
118             strcpy(mystr,temp);
119             len = strlen(mystr);
120         }
121         else{
122             break;
123         }  
124     }
125     delete []temp;
126 }
127 void fun(char *s,char str[][256]){
128     int index = 0;
129     char *p = s,*q = s;
130     while(*p)
131     {
132         if(*p==','){
133             *p = '\0';
134             strcpy(str[index++],q);
135             q = p+1;
136         }
137         p++;
138     }
139     strcpy(str[index++],q);    
140     /* for(int i=0;i<9;++i){
141         printf("%s\n",str[i]);
142     } */
143 }
144 int main()
145 {   //testt     esttest,3,test,t,a,test,str,t,es
146     char s[256] = "";
147     char str[9][256]={0};    
148     gets(s);
149     fun(s,str);    
150     /* 1.實現int IsSubString(int start, const char *str); */
151     //---------------------s0,count1,s2
152     EditString es1(str[0]);
153     cout<<es1.IsSubString(atoi(str[1]),str[2])<<",";//4
154     /* 2.實現EditChar(char s, char d)*/
155     //---------------------s0,c3,c4
156     EditString es2(str[0]);
157     es2.EditChar(str[3][0],str[4][0]);
158     es2.showStr();  //"aesaaesaaesa"
159     cout<<",";
160     /* 3.實現void EditSub(char * subs,char *subd)*/ 
161     //---------------------s5,s6    
162     EditString es3(str[0]);
163     es3.EditSub(str[5],str[6]);
164     es3.showStr();//"strstrstr"
165     cout<<",";
166     /* 4.實現void DeleteChar(char ch) */
167     //---------------------c7
168     EditString es4(str[0]);
169     es4.DeleteChar(str[7][0]);
170     es4.showStr();//"eseses"
171     cout<<",";
172     /* 5.實現void DeleteSub(char * sub)*/ 
173     //--------------s8
174     EditString es5(str[0]);
175     es5.DeleteSub(str[8]);//"tttttt";
176     es5.showStr();
177     cout<<endl;
178     return 0;
179 }

4、完備數

如果一個數正好是他的所有約數(除了它本身以外)的和,稱為完備數,

如:6,它的約數有1,2,3,並且1+2+3=6.

請輸出n以內的所有完備數(完備數遞增輸出),每個完備數1行,每行按照下例輸出:

比如某完備數是6,則該行輸出:6=1+2+3

如果輸入錯誤,則輸出"error"。

例如:

輸入:

40

輸出:

6=1+2+3空格回車

28=1+2+4+7+14空格回車

 1 #include<stdio.h>
 2 
 3 int fun(int i)
 4 {
 5     int sum=0;
 6     int t = i-1,j;
 7     int arr[100] = {0};
 8     int index =0;
 9     while(t)
10     {
11         
12         if(i%t==0)
13         {
14             arr[index++] = t;
15             sum += t;
16             //printf("%d,%d,%d\n",i,sum,t);
17         }
18         t--;
19     }
20     if(sum==i){
21         printf("%d=",i);
22         for( j=index-1; j>=0; --j)
23         {
24             if(j<index-1&&index!=1)
25                 printf("+");
26             printf("%d",arr[j]);
27         }
28         return 1;
29     }
30     return 0;
31 }
32 
33 int main()
34 {
35     int n,flag=0;
36     scanf("%d",&n);
37    
38     for(int i=6;i<=n;++i)
39     {
40         if(fun(i)){
41             if(flag>1)
42                 printf("\n");
43             else{
44                 printf(" \n");
45             }
46             flag++;
47         }
48     }    
49     return 0;
50 }

5、逆序memcpy

實現逆序的Memcpy方法。

void * reversememcpy ( void * destination, const void * source, int num );

從source所指的內存地址的起始位置開始拷貝num個字節,逆序保存到目標destination所指的內存地址的

起始位置中。返回destination首地址。

注意為逆序拷貝。比如source指向的位置,依次保存了abcdef,當num=3時,則逆序拷貝后destination指向的

位置應該依次保存cba.

輸入:abcdef

輸出:cba

提交的程序包括main函數,具體內容如下:

#include<stdio.h>
#include<string.h>
void * reversememcpy ( void * destination, const void * source, int num );
int main()
{
    char source[100],destionation[100];
    int n;
    scanf("%s",source);
    scanf("%d".&n);
    destionation=reversememcpy (destionation,scource,strlen(source),n);
    printf("%s",destionation);
    return 0;
} 

注意:目標地址不能為空,源和目標空間首地址差應該大於num。如果num>strlen(source),應該輸出error

 1 #include<stdio.h>
 2 #include<string.h>
 3 void * reversememcpy ( void * destination, const void * source, int num )
 4 {
 5     char *des = (char*)destination, *src = (char*)source;
 6     if(strlen(src)<num){
 7         printf("error");
 8         return NULL;
 9     }
10     
11     for(int i=0; i<num; ++i)
12     {
13         des[num-i-1] = src[i];
14     }
15     return destination;
16 }
17 
18 int main()
19 {
20     char source[100]="",destination[100]="";
21     int n; 
22     gets(source);
23     scanf("%d",&n);
24     
25     reversememcpy (destination,source,n);
26     printf("%s",destination);
27     return 0;
28 }

6、冒泡排序

題目內容:

輸入n個整數,用冒泡排序對這n個數進行遞增/非遞減排序,輸出排序后的結果.如果輸入不符要求,則輸出"error"

輸入格式:第一行是待排序的數據個數n,第二排是逗號分隔的n個正整數

9

9,8,7,6,5,4,3,2,1

輸出格式:輸出排序后的用逗號分隔的n個數據,最后1個數據后面沒有逗號

1,2,3,4,5,6,7,8,9

 1 #include <stdio.h>
 2 #define N 100
 3 /*冒泡排序--遞歸*/
 4 void BubbleSort(int *a,int left, int right)
 5 {
 6     if(left<right){
 7         int j,t; 
 8         for(j=right; left<j; j--){
 9             if(a[j-1]>a[j])/*相鄰比較*/ 
10                 t=a[j],a[j]=a[j-1],a[j-1]=t;  
11         }
12         BubbleSort(a,j+1,right);/*遞歸*/
13     }
14 }
15 
16 int main()
17 {
18     int arr[N] ={0};
19     int t,n;
20     int ret = scanf("%d",&n);
21     if(!ret){
22         printf("error");return 0;
23     }
24     
25     for(int i=0; i<n-1; ++i)
26     {
27         int ret = scanf("%d,",&arr[i]);
28         if(!ret){
29                 printf("error");return 0;
30         }
31     }
32     scanf("%d,",&arr[n-1]);
33    
34     BubbleSort(arr,0,n-1);
35     for(int i=0; i<n; ++i){
36         if(i&&n>1)printf(",");
37         printf("%d",arr[i]);
38     }
39     printf("\n");
40     
41     return 0;
42 }

7、實現三角形類

實現一個三角形類 Ctriangle

該類有一個GetPerimeter方法返回三角形的周長;

GetArea方法返回三角形的面積;

該類還提供一個display方法顯示三角形的三邊長度;

最終在main函數中生成該類,

輸入三條邊的長度(不用考慮三條邊不能構成三角形的情況);

展示三角形的三邊長度以及周長和面積

Ctriangle類的使用如下,在你的代碼中除了實現Ctriangle類還需引入一下代碼。

int main() 
{
    double a, b, c;
    cin >> a >> b >> c;
    Ctriangle T(a, b, c);
    T.display();
    cout << "Perimeter:" <<setprecision(4)<< T.GetPerimeter() << endl;
    cout << "Area:" << setprecision(5) << T.GetArea() << endl;
    system("pause");
    return 0;
}

輸出格式

輸入:3 4 5

輸出:

Ctriangle:a=3,b=4,c=5

Perimeter:12

Area:6

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cmath>
 4 #include <iomanip>
 5 using namespace std;
 6 class Ctriangle
 7 {
 8 protected:
 9     double a,b,c;
10 public:
11     Ctriangle(double x,double y,double z)
12     {
13        a=x;b=y;c=z;
14     }
15     double GetPerimeter()
16     {
17         return a+b+c;
18     }
19     double GetArea()
20     {
21         double p = (a+b+c)/2;
22         return sqrt(p*(p-a)*(p-b)*(p-c));
23     }
24     void display()
25     {
26         cout<<"Ctriangle:a="<<a<<",b="<<b<<",c="<<c<<endl;
27     }
28 };
29 
30 int main()
31 {
32     double a, b, c;
33     cin >> a >> b >> c;
34     Ctriangle T(a, b, c);
35     T.display();
36     cout << "Perimeter:" <<setprecision(4)<< T.GetPerimeter() << endl;
37     cout << "Area:" << setprecision(5) << T.GetArea() << endl;
38     system("pause");
39     return 0;
40 }

 

 


免責聲明!

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



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