西安交大C++程序设计第六章作业2
- 格式:doc
- 大小:850.50 KB
- 文档页数:24
西安交大c++程序设计第六章作业Document number:NOCG-YUNOO-BUYTT-UU986-1986UT西安交通大学实验报告课程__计算机程序设计__实验名称__指针与函数__第 1 页共 25 页系别____ _______ 实验日期 2014 年 4月 18日专业班级__ ____组别_____________ 实验报告日期 2014 年 4 月 19日姓名___ _______学号_ _报告退发 ( 订正、重做 )同组人_________________________________ 教师审批签字一、实验目的学会使用递归函数和函数重载,进一步熟练动态分配等指针使用方法。
二、实验内容(一)第一题:1、(必做题)使用递归算法编写如下程序:对于任意给定的实数 X 和整数k( k>0) ,计算 Xk 。
1.源程序代码:#include<iostream>using namespace std;double yunsuan(double x,int k);验结果:(1)输入X正实数:(2)输入X正整数:(3)输入x为负数:(4)输入k为负数:3.问题分析:该函数的循环方式是:x^k=x*x^(k-1).设f(x,k)=x^k,那么就有f(x,k)=f(x,k-1)*x.而其结束递归的条件是k=1,此时有f(x,1)=x,由此给出初值。
(二)第二题:使用递归算法编写求斐波那契数列的第 n 项的函数,并编出主函数进行验证。
1.源程序代码:#include<iostream>using namespace std;int fib(int n)验结果:(1)输入项数正确(0或正整数):(2)输入项数有误(负数):3.问题分析:该题的递归方式:第n项为之前两项之和,即:fib(n)=fib(n-1)+fib(n-2),由此递归至fib(1)和fib(2)时结束递归,而fib(1)和fib(2)已知。
习题及实验解答第六章一、选择题1、应为4(无正确选项)2、D3、B C4、D5、A6、A7、C8、B9、A 10、A二、程序填空1、stu[i].score k=j p[k]=p[i] p[i]=temp2、p!=NULL p->data p->next3、struct node * s->data=ch r=s NULL三、编程题1、#include "iostream.h"struct staff{char num[6];char name[8];float salary[3]; //分项工资float gs; //实得工资}s[100];void main( ){int i,j,n;cin>>n; /*输入职工人数*/for(i=0;i<n;i++){cin>>s[i].num>>s[i].name;for(j=0;j<3;j++)cin>>s[i].salary[j];}cout<<"NO. salary\n";for(i=0;i<n;i++){s[i].gs= s[i].salary[0]+ s[i].salary[1]- s[i].salary[2] ;cout<<s[i].num<<'\t'<<s[i].gs<<endl;}}2、#include "iostream.h"#include "stdio.h"struct str{char ch;struct str *next;};void main(){char s[100];int i=0,num=0;struct str *insert,*head=NULL,*p;gets(s);while(s[i]!='\0'){insert=new str;insert->ch=s[i];if(head==NULL){head=insert ;head->next=NULL;}else{insert->next=head ;head=insert;}i++;}p=head;while(p!=NULL){if(p->ch>='A'&&p->ch<='Z')num++;cout<<p->ch;p=p->next;}cout<<endl<<"num="<<num<<endl; }3、#include "iostream.h"#include "stdio.h"struct node{char ch;int count;struct node *next;};void main( ){struct node *head,*p1,*p2,*insert;char c;head=NULL;while((c=getchar())!='\n'){p1=head;while(p1!=NULL&&c>p1->ch){p2=p1;p1=p1->next;}if(p1==NULL){insert=new node;insert->ch=c;insert->count=1;if(head==NULL){insert->next=head;head=insert;}else{insert->next=NULL;p2->next=insert;}}else if(c==p1->ch)p1->count++;else{insert=new node;insert->ch=c;insert->count=1;if(p1==head){insert->next=head;head=insert;}else{insert->next=p1;p2->next=insert;}}}p1=head;while(p1!=NULL){cout<<p1->ch<<' '<<p1->count<<'\t';p1=p1->next;}}4、#include "stdio.h"#include "iostream.h"struct node{int coef;int expn;struct node *next;};struct node *creat(){struct node *head,*tail,*p;int c,e;head=NULL;cin>>c>>e;while(c!=0) //约定以输入系数为0作为多项式的结束{p=new node;p->coef=c;p->expn=e;if(head==NULL)head=p;elsetail->next=p;tail=p;cin>>c>>e;}tail->next=NULL;return head;}void print(struct node *h){struct node *p;p=h;while(p!=NULL){if(p->next!=NULL)cout<<p->coef<<'x'<<p->expn<<'+';else{if(p->coef!=0&&p->expn!=0)cout<<p->coef<<'x'<<p->expn<<endl;else if(p->coef!=0)cout<<p->coef<<endl;elsecout<<endl;}p=p->next;}}void main(){struct node *h1,*p1,*h2,*p2,*h3,*p3,*newnode,*t3;h1=creat();print(h1);h2=creat();print(h2);p2=h2;h3=NULL;p1=h1;p2=h2;p3=h3;t3=h3;while(p1!=NULL&&p2!=NULL){newnode=new node;if(p1->expn>p2->expn){newnode->coef=p1->coef;newnode->expn=p1->expn;p1=p1->next;}else if(p1->expn<p2->expn){newnode->coef=p2->coef;newnode->expn=p2->expn;p2=p2->next;}else{newnode->coef=p2->coef+p1->coef;newnode->expn=p2->expn;p2=p2->next;p1=p1->next;}if(h3==NULL){h3=newnode;t3=newnode;}elset3->next=newnode;t3=newnode;}if(p1==NULL)t3->next=p2;elset3->next=p1;print(h3);}第七章一、选择题1、D2、B3、B4、A5、B6、A7、D8、B9、C 10、B二、程序填空1、fname, “w”(ch=getchar())!=’#’count++2、(c=fgetc(fp)) length++ length=03、”wb”&emp, sizeof(employer),1,fp fclose(fp) “rb”&emp, sizeof(employer),1,fp三、编程题1、#include "iostream.h"#include "stdlib.h"#include "stdio.h"void main(){FILE *fp1,*fp2;char ch;fp1=fopen("f1.txt","a");if(fp1==NULL){cout<<"can't open f1.\n";exit(1);}if((fp2=fopen("f2.txt","r"))==NULL){cout<<"can't open f2.\n";exit(1);}while(1){ch=fgetc(fp2);if(feof(fp2))break;cout<<ch;fputc(ch,fp1);}fclose(fp1);fclose(fp2);}2、#include "iostream.h"#include "stdlib.h"#include "stdio.h"void main(){FILE *fp;int a[10],i,j;if((fp=fopen("d1.dat","w"))==NULL){cout<<"can't open d1.\n";exit(1);}for(i=0;i<10;i++)a[i]=rand();for(i=0;i<9;i++)for(j=0;j<9-i;j++)if(a[j]<a[j+1]){int t=a[j];a[j]=a[j+1];a[j+1]=t;}for(i=0;i<10;i++)fprintf(fp,"%d\t",a[i]);fclose(fp);}3、#include "iostream.h"#include "stdlib.h"#include "stdio.h"#include "string.h"void main(){FILE *fp;char s[100];int a[26]={0},i;if((fp=fopen("f.txt","r"))==NULL){cout<<"can't open f.\n";exit(1);}fgets(s,100,fp);strlwr(s);i=0;while(s[i]!='\0'){if(s[i]>='a'&&s[i]<='z')a[s[i]-'a']++;i++;}for(i=0;i<26;i++)cout<<(char)('a'+i)<<":"<<a[i]<<endl;fclose(fp);}4、#include "iostream.h"#include "stdlib.h"#include "stdio.h"struct student{char num[8];char name[20];double s[3],ave;}st[5];void main(){student stu[5];FILE *fp;int i;if((fp=fopen("stu","wb"))==NULL){cout<<"can't open stu.\n";exit(1);}for(i=0;i<5;i++){cin>>stu[i].num>>stu[i].name>>stu[i].s[0]>>stu[i].s[1]>>stu[i].s[2];stu[i].ave=(stu[i].s[0]+stu[i].s[1]+stu[i].s[2])/3;}fwrite(stu,sizeof(student),5,fp);fclose(fp);}第八章一、选择题1、A2、A3、C4、C5、6、D7、B8、D9、C 10、B11、D 12、A 13、B 14、D 15、D二、阅读程序写结果1、con1 calledcon2 calledcon3 calleda=0,b=0a=10,b=10a=10,b=202、0 51 52 53 54 53、4564、10,106,67,95、x=0x=10x=7三、编程题1、#include "iostream.h"#include "string.h"class Cat{private:int age;double weight;char color[10];public:void set(int a,double w,char c[10]){age=a;weight=w;strcpy(color,c);}void print(){cout<<"age:"<<age<<"\tweight:"<<weight<<"\color:"<<color<<endl;}int getage(){return age;}double getweight(){return weight;}char *getcolor(){return color;}};void main(){Cat c1;int a;double w;char c[10];cin>>a>>w>>c;c1.set(a,w,c);c1.print();}2、#include "iostream.h"#include "string.h"#include "stdio.h"class Mystring{private:char *str;public:Mystring(){ }Mystring(char *s){str=new char[100];strcpy(str,s);}void set(char *s){str=new char[100];strcpy(str,s);}void print(){cout<<str<<endl;}int length( ){int i=0;while(str[i]!='\0')i++;return i;}char *stringcat(Mystring s2){int i=0,j=0;while(str[i]!='\0')i++;while(s2.str[j]!='\0')str[i++]=s2.str[j++];str[i]='\0';return str;}};void main(){Mystring s1;char s[100];gets(s);s1.set(s);s1.print();gets(s);Mystring s2(s);s2.print();cout<<s1.stringcat(s2);}3、#include "iostream.h"#include "string.h"#include "stdio.h"class Point{private:double x,y;public:Point(){ }Point(double x1,double y1){x=x1;y=y1;}void set(double x1,double y1){x=x1;y=y1;}void move(double x1,double y1){x=x+x1;y=y+y1;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}double getx(){ return x;}double gety(){ return y;}};class Circle:public Point{private:double r;public:void set(double x1,double y1,double r1){Point::set(x1,y1);r=r1;}void print(){Point::print();cout<<r<<endl;}double getr(){ return r;}double s(){ return 3.14*r*r;}};void main(){Point p1;Circle c1;double x1,y1,r1;cin>>x1>>y1;p1.set (x1,y1);p1.print ();cin>>x1>>y1;p1.move (x1,y1);p1.print ();cin>>x1>>y1>>r1;c1.set (x1,y1,r1);c1.print ();cout<<c1.s()<<endl;}4、#include "iostream.h"class Point{private:int x,y;public:Point(){ }Point(int x1,int y1){ x=x1; y=y1;}friend Point operator+(Point &p1,Point &p2){Point p(p1.x+p2.x,p1.y+p2.y);return p;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}};void main(){Point p1(1,2),p2(2,3),p3;p3=p1+p2;p3.print();}5、#include "iostream.h"#include "stdio.h"#include "string.h"class Teacher{private:char name[20];public:void virtual input(){cout<<"input name:";cin>>name;}virtual double wage()=0;void virtual print(){cout<<name<<'\t';}};class Professor:public Teacher{private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (3000+40*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};class ViceProfessor:public Teacher {private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (2500+30*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};class Lecture:public Teacher{private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (2000+25*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};void main(){Teacher *t;Professor *p;ViceProfessor *vp;Lecture *l;char ptitle[20],ch;//职称do{cout<<"input ptitle(professor,viceprofessor or lecture):"<<endl;gets(ptitle);if(!strcmp(ptitle,"professor")){p=new Professor;t=p;}else if(!strcmp(ptitle,"viceprofessor")){vp=new ViceProfessor;t=vp;}else{l=new Lecture;t=l;}t->input ();t->print ();cout<<"continue(y/n)?";cin>>ch;}while(ch=='y');}。
在下列代码中,有(B )处实现了拆箱。
int score=5;object o= score;o=10;score =(int)o;object oScore = score;A.2B.1C.0D.32单选(2分)下面控制对成员访问描述错误的是(B )A.如果一个类试图去使用另一个类的私有成员,则编译器会产生错误消息,提示这些私有成员无法访问B.如果类的成员没有用访问修饰符声明,则默认为共有的C.类的私有变量、属性和方法时类的对象无法直接访问的D.访问修饰符public和private控制着对类的变量、方法和属性的访问3单选(2分)有关this引用访问当前对象成员的描述正确的是(D)A.调用特定对象的的非静态方法时,方法体会显式用this引用这个对象的实例变量、其他方法和属性B.如果方法包含与字段同名的局部变量,则方法将引用字段而不是局部变量C.方法中的参数名或局部变量名应尽可能和字段名保持一致,方便阅读D.每个对象都可以用关键字this引用自己4单选(2分)有关构造函数的说法,错误的是()A.要重载构造函数,只需提供具有不同签名的多个构造函数声明B.每个类都必须至少有一个构造函数C.当实现类的方法时,应使用类的属性来访问类的私有数据,这样可以减少代码维护的工作量,降低出错的可能性D.不管是否显式的声明了构造函数,编译器都会创建默认的构造函数5单选(2分)有关析构函数和内存回收的描述正确的是(B)A.在内存回收期回收对象的内存之前,析构函数由内存回收期调用,执行终止清理工作。
析构函数和构造函数类似,可以重载B.析构函数没有任何修饰符、没有任何参数、也不返回任何值C.析构函数的名字由符号“~”加类名组成,其中“~”可以省略D.析构函数可以被自动调用,也可以主动显示的调用下面对readonly和const修饰的实例变量不正确的是(D )A.动态常量(readonly)的值则是在运行的那一刻才获得的,编译器编译期间将其标示为只读常量,而不用常量的值代替,这样动态常量不必在声明的时候就初始化,而可以延迟到构造函数中初始化。
西安交通大学实验报告课程__计算机程序设计__实验名称_课外实验题目__第 1 页共 19 页系别___ _______ 实验日期 2014 年 4月 3日专业班级____组别_____________ 实验报告日期 2014 年4 月 5日姓名___ _____学号_ _报告退发 ( 订正、重做 )同组人_________________________________ 教师审批签字一、实验目的复习巩固本阶段所学的知识,包括数组的使用、函数的使用、循环语句和条件语句的使用等。
二、实验内容(一)第一题:1、编写一个程序,计算m~n范围内的每个正整数的全部素因子。
其中的m和n由键盘输入。
评分标准:(1)程序框架完整,代码规范;(20%)(2)数据类型的定义和使用方法正确;(20%)(3)程序控制结构使用正确;(20%)(4)算法正确,清晰合理;(20%)(5)运行结果正确,输入和输出格式如下所示。
(20%)请输入m和n:15 1815的非平凡因子:3 516的非平凡因子:2 4 817的非平凡因子:18的非平凡因子:2 3 6 91.源程序代码:#include<iostream>using namespace std;void suyinzi(int x);int main(){int m,n;cout<<"请输入正整数m和n(m<=n):";cin>>m>>n;while(m>n){cout<<"您输入有误,m应该小于等于n,请重新输入:";cin>>m>>n;}for(int j=m;j<=n;j++)//对于范围内的正整数逐一判断寻找因子{suyinzi(j);}return 0;}void suyinzi(int x)//寻找并输出x的所有非平凡因子{cout<<x<<"的非平凡因子为:";for(int i=2;i<=x/2;i++){if(x%i==0){cout<<i<<" ";}}cout<<endl;}2.实验结果:3.问题分析:此题简单,但当该数没有非平凡因子时,如能够输出:“x没有非平凡因子!”而非仅仅输出空白则更好。
第1章 C++语言简介1.在计算机上调试运行本章的所有例题,熟悉实验环境和方法。
2.仿照例1-3,编写一个计算矩形面积的程序。
3.乘法计算器程序:可以根据例1-4自行改编。
4.修改例1-5的生日卡程序,使其能够输入和显示日期。
5.使用梯形法计算下式定积分的值。
⎰-+11sin dx e x x积分区域等分数可取为200,并将计算结果和手算结果相比较。
提示:e x 用math.h 中得库函数exp(x)表示。
第2章 控制结构1.编写计算阶乘 n!的程序。
2.编写程序求斐波那契数列的第n 项和前n 项之和。
斐波那契数列是形如0, 1, 1, 2, 3, 5, 8, 13, ...其通项为:F 0 = 0;F 1 = 1;F n = F n -1+F n -2。
3.编程求 ...)12()!(2)!2(...5423132arcsin 221252++++⋅⋅⋅⋅+⋅+≈+n n x n x x x x n n ,其中1<x 。
提示:结束条件可用 ε<u ,其中u 为通项。
4.求解猴子吃桃问题。
猴子在第一天摘下若干个桃子,当即就吃了一半,又感觉不过瘾,于是就多吃了一个。
以后每天如此,到第10天时,就只剩下了一个桃子。
请编程计算第一天猴子摘的桃子个数。
5.用弦截法求一元方程0)(=x f 在区间[]10,x x 之间的一个根。
提示:考虑当区间[]10,x x 足够小,在此区间中方程0)(=x f 仅有一个单根的情况,如图2.14所示。
图2.14 弦截法求方程的解此时如)(0x f 和)(1x f 异号,则可用两点间直线公式求出x 2:)()()(0101002x f x f x f x x x x ---= 然后用x 2代入原式求出f (x 2),判断f (x 2)与f (x 1)和f (x 0)中的哪一个同号,就用x 2和f (x 2)代替之,即如果f (x 2)和f (x 0)同号,就用x 2和f (x 2)代替x 0和f (x 0),反之用x 2和f (x 2)代替x 1和f (x 1),然后再继续上述过程直至|x 2-x 0|或|x 2-x 1|小于给定的误差控制值。
Exercise6_2#include <iostream>using namespace std;int main(){// Prompt the user to enter the first numbercout << "Enter an integer: ";int max;cin >> max;int count = 1;// Prompt the user to enter the remaining five numbers for (int i = 1; i <= 5; i++) {cout << "Enter an integer: ";int temp;cin >> temp;if (temp > max) {max = temp;count = 1;}else if (temp == max)count++;}cout << "\n" <<"max is " << max << "\n" <<"the occurrence count is " << count;return 0;}Exercise6_4#include <iostream>using namespace std;int main(){double scores[100];double sum = 0;int count = 0;do{cout << "Enter a new score: ";cin >> scores[count];sum += scores[count];}while (scores[count++] >= 0);double average = (sum - scores[count]) / (count - 1);int numOfAbove = 0;int numOfBelow = 0;for (int i = 0; i < count - 1; i++)if (scores[i] >= average)numOfAbove++;elsenumOfBelow++;cout << "Average is " << average << endl;cout << "Number of scores above or equal to the average " << numOfAbove << endl; cout << "Number of scores below the average " << numOfBelow << endl;return 0;}Exercise6_6#include <iostream>#include <cmath>using namespace std;int main(){const int NUM_OF_PRIMES = 50;// Store prime numbersint primeNumbers[NUM_OF_PRIMES];int count = 0; // Count the number of prime numbersint number = 2; // A number to be tested for primenessbool isPrime = true; // Is the current number prime?cout << "The first 50 prime numbers are \n";// Repeatedly find prime numberswhile (count < NUM_OF_PRIMES){// Assume the number is primeisPrime = true;// Test if number is primefor (int i = 0; i < count && primeNumbers[i] <= sqrt(1.0 * number); i++) {//If true, the number is not primeif (number % primeNumbers[i] == 0){// Set isPrime to false, if the number is not primeisPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime){primeNumbers[count] = number;count++; // Increase the countif (count % 10 == 0){// Print the number and advance to the new linecout << number << endl;}elsecout << number << "\t";}// Check if the next number is primenumber++;}return 0;}Exercise6_8#include <iostream>#include <cmath>using namespace std;int average(int array[], int size) {int sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}double average(double array[], int size) { double sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}int main(){int list1[] = {1, 2, 3, 4, 5, 6};double list2[] = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5};cout << average(list1, 6) << endl;cout << average(list2, 6) << endl;return 0;}Exercise6_10#include <iostream>#include <cmath>using namespace std;int minIndex(int list[], int size){int min = list[0];int minIndex = 0;for (int i = 1; i < size; i++)if (min > list[i]){min = list[i];minIndex = i;}return minIndex;}int main(){int list[] ={1, 2, 4, 5, 10, 100, 2, -22};cout << "The index of the min is " << minIndex(list, 8) << endl;return 0;}Exercise6_12#include <iostream>using namespace std;void reverse(int list[], int size){for (int i = 0, j = size - 1; i < size / 2; i++, j--){int temp = list[i];list[i] = list[j];list[j] = temp;}}int main(){int myList[] ={1, 2, 3, 4, 5, 6, 7, 8};reverse(myList, 8);for (int i = 0; i < 8; i++)cout << myList[i] << " ";return 0;}Exercise6_14#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;int main(){int list[100000];for (int i = 0; i < 100000; i++){list[i] = rand();}int key = rand();long startTime = time(0);cout << linearSearch(list, key, 100000) << endl;long endTime = time(0);cout << "End time: " << endTime << endl;cout << "Start time: " << startTime << endl;long executionTime = endTime - startTime;cout << "Execution time for linear search is " << executionTime << endl; selectionSort(list, 100000);startTime = time(0);cout << binarySearch(list, key, 100000) << endl;endTime = time(0);executionTime = endTime - startTime;cout << "Execution time for binary search is " << executionTime << endl;return 0;}Exercise6_16#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;/** The method for printing numbers */void printList(double list[], int size){for (int i = 0; i < size; i++)cout << list[i] << " ";cout << endl;}void bubbleSort(double list[], int size) {bool changed = true;do{changed = false;for (int j = 0; j < size - 1; j++)if (list[j] > list[j + 1]){//swap list[j] wiht list[j+1]double temp = list[j];list[j] = list[j + 1];list[j + 1] = temp;changed = true;}}while (changed);}int main(){// Initialize the listdouble myList[] ={5.0, 4.4, 1.9, 2.9, 3.4, 3.5};// Print the original listcout << "My list before sort is: "; printList(myList, 6);// Sort the listbubbleSort(myList, 6);// Print the sorted listcout << "\nMy list after sort is: " << endl; printList(myList, 6);return 0;}Exercise6_18#include <iostream>using namespace std;int main(){int m[4] [4] ={{1, 2, 4, 5},{6, 7, 8, 9},{10, 11, 12, 13},{14, 15, 16, 17}};int sum = 0;for (int i = 0; i < 4; i++)sum += m[i] [i];cout << "Sum of diagonal is " << sum << endl;return 0;}Exercise6_20#include <iostream>using namespace std;/** The method for sorting the numbers */void sortAndKeepIndex(int list[], int indexList[], int size) { int currentMax;int currentMaxIndex;// Initialize indexListfor (int i = 0; i < size; i++)indexList[i] = i;for (int i = size - 1; i >= 1; i--) {// Find the maximum in the list[0..i]currentMax = list[i];currentMaxIndex = i;for (int j = i - 1; j >= 0; j--) {if (currentMax < list[j]) {currentMax = list[j];currentMaxIndex = j;}}// Swap list[i] with list[currentMaxIndex] if necessary;if (currentMaxIndex != i) {list[currentMaxIndex] = list[i];list[i] = currentMax;// Swap the index in indexList tooint temp = indexList[i];indexList[i] = indexList[currentMaxIndex];indexList[currentMaxIndex] = temp;}}}int main(){const int NUMBER_OF_WORKERS = 8;double workHours[NUMBER_OF_WORKERS][7] = {{2, 4, 3, 4, 5, 8, 8},{7, 3, 4, 3, 3, 4, 4},{3, 3, 4, 3, 3, 2, 2},{9, 3, 4, 7, 3, 4, 1},{3, 5, 4, 3, 6, 3, 8},{3, 4, 4, 6, 3, 4, 4},{3, 7, 4, 8, 3, 8, 4},{6, 3, 5, 9, 2, 7, 9}};// Create an array to store total weekly hoursint weeklyHours[NUMBER_OF_WORKERS] = {0, 0, 0, 0, 0, 0, 0, 0};for (int i = 0; i < NUMBER_OF_WORKERS; i++)for (int j = 0; j < 7; j++)weeklyHours[i] += workHours[i][j];int indexList[NUMBER_OF_WORKERS];// Sort weeklyHourssortAndKeepIndex(weeklyHours, indexList, NUMBER_OF_WORKERS);// Display resultfor (int i = NUMBER_OF_WORKERS - 1; i >= 0; i--)cout << "Employee " << indexList[i] << ": " <<weeklyHours[i] << endl;return 0;}Exercise6_22#include <iostream>using namespace std;const int COLUMN_SIZE = 5;/** The method for multiplying two matrices */void multiplyMatrix(int a[] [COLUMN_SIZE], int b[] [COLUMN_SIZE], int result[] [COLUMN_SIZE], int rowSize){for (int i = 0; i < COLUMN_SIZE; i++)for (int j = 0; j < COLUMN_SIZE; j++)for (int k = 0; k < COLUMN_SIZE; k++)result[i] [j] += a[i] [k] * b[k] [j];}/** Print result */void printResult(int m1[] [COLUMN_SIZE], int m2[] [COLUMN_SIZE], int m3[] [COLUMN_SIZE], char op, int rowSize){for (int i = 0; i < rowSize; i++){for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m1[i] [j];if (i == COLUMN_SIZE / 2)cout << " " << op << " ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m2[i] [j];if (i == COLUMN_SIZE / 2)cout << " = ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m3[i] [j];cout << endl;}}int main(){// Create two matrices as two dimensional arraysint matrix1[5] [5];int matrix2[5] [5];int result[5] [5];// Assign random values to matrix1 and matrix2for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++){matrix1[i] [j] = rand();matrix2[i] [j] = rand();}multiplyMatrix(matrix1, matrix2, result, 5);cout << "The multiplication of the matrices is " << endl; printResult(matrix1, matrix2, result, '*', 5);}Exercise6_24#include <iostream>using namespace std;int main(){int board[8] [8];for (int i = 0; i < 8; i++){for (int j = 0; j < 8; j++){board[i] [j] = rand() % 2;cout << board[i] [j];}cout << endl;}// Check rowsfor (int i = 0; i < 8; i++){bool same = true;for (int j = 1; j < 8; j++){if (board[i] [0] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[i] [0] << "'s on row " << i << endl;}// Check columnsfor (int j = 0; j < 8; j++){bool same = true;for (int i = 1; i < 8; i++){if (board[0] [j] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[0] [j] << "'s on column " << j << endl; }// Check major diagonalbool same = true;for (int i = 1; i < 8; i++){if (board[0] [0] == board[i] [i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on major diagonal" << endl;// Check subdiagonalsame = true;for (int i = 1; i < 8; i++){if (board[0] [7] == board[i] [7 - i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on subdiagonal" << endl;return 0;}Exercise6_26#include <iostream>#include <cmath>using namespace std;int lcm(int number1, int number2);int pow(int a, int b);int getPrimeFactors(int number, int table[][2]);int main(){// Enter two integersint number1;cout << "Enter the first integer: ";cin >> number1;int number2;cout << "Enter the second integer: ";cin >> number2;cout << "The LCM for " << number1 << " and " << number2 << " is " << lcm(number1, number2) << endl;}int lcm(int number1, int number2){int table1[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table1[i][j] = 0;int i1 = getPrimeFactors(number1, table1);int table2[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table2[i][j] = 0;int i2 = getPrimeFactors(number2, table2);int result = 1;int i = 0;int j = 0;while (i < i1 && j < i2){if (table1[i] [0] < table2[j] [0]){result *= pow(table1[i] [0], table1[i] [1]);i++;}else if (table1[i] [0] == table2[j] [0]){result *= pow(table1[i] [0], max(table1[i] [1], table2[j] [1]));i++;j++;}else{result *= pow(table2[j] [0], table2[j] [1]);j++;}}while (i < i1){result *= pow(table1[i] [0], table1[i] [1]);i++;}while (j < i2){result *= pow(table2[j] [0], table2[j] [1]);j++;}return result;}int pow(int a, int b){int result = 1;for (int i = 1; i <= b; i++)result *= a;return result;}int getPrimeFactors(int number, int table[][2]) {int i = 0;int factor = 2;while (factor <= number){if (number % factor == 0){table[i] [0] = factor;while (number % factor == 0){number = number / factor;table[i] [1] ++;}i++;}else{factor++;}}return i;}。
6-3 (1)#include <iostream>using namespace std;int main(void){int num[10], *p, i, j, temp; cout«**输入10 个整数"vvendl; for(i=0; i<10; i++){ cin»num[订;}for(i=0; i<10; ■++){// 0, 1_________ 8p = &num[i];for(j = i+1; J<10; j++){//1, 2・.・ 9 if(num[i]<=num[J]){p = &num[j];}}cout«*p«endl; temp = *p;*p = num[i]; num[i] = temp;}system(M pause f,);return 0;(2)注:N的数值可以在宏定义中更改,以下是W12的吋候:#include <iostream>using namespace std;#define N 12struct N0DE{int num;NODE *next;};int i:class List{private:NODE list[N];NODE *temp;public:List() {//设置一个结点组成的圈temp = Iist;Iist[0].num = 1 ;Iist[0].next = &list[1];//第一个结点己经完成for(i=1: i<(N-1); ■++){Iist[i].num = i+1:Iist[i].next = &Iist[i+1];}//第二个至倒数第二个已经完成Iist[N-1].num = N;Iist[N-1].next = &list[O];//最后一个结点已经完成void Next2(){temp = temp->next;temp = temp->next;}void Fun(){temp = & list[N-1];//得到链表的最后一个结点地址do{Next2();//当前是0,数到2〃现在temp已经是标号为2的结点的地址了cout«(temp->next)->num«ff M;//$ny出要被删除的结点(p+1) temp->next = (temp->next)->next ;//^ 被删除的结点的前一个(p)和后一个相连接(p+2)}while(temp->next != (temp->next)->next); cout«temp->num;}};int main(void){List one; one.Fun(j; system(ft pause f,); return 0;}(3)#include <iostream>#include <string> using namespace std;#define SIZE 512class Str{private:char str1[SIZE]:char str2[SIZE];char *p;int i, length;public:void set(){cout«ff输入第一个字符串:ff«endl; cin>>str1;cout«ff输人第二个字符串:ft«endl; cin>>str2;}void fun(){Iian(str1, str2):}void Iian(char *m, char *n){ length = strlen(n); for(i=0; i<strlen(n)+1; i++){ P = & n[i];str1 [length+i] = *p;}cout«ft连接之后的结果:\n ft«str1«endl;}};int main(void){ Str one; one.set(); one.funO; system(ft pause f,); return 0;}(4)#include <iostream>#include <string>using namespace std;#define SIZE 512class Str{private:char str[SIZE]:int upper, lower, space, number, other, i:public:Str(){upper=Iower=space=number=other=0;void set(){cout«ff输入一个字符ff«endl;gets(str);}void check(){for(i=0; i<strlen(str); i++){if(str[i]>=w A・ && str[i]<="Z>){upper++;}else if(str[i]>=w a w && str[i]<=w z w){lower++;}else if(str[i]=="・){space++;}else if(str[i]>=w O w && str[i]<=w9w){number++;}else{other++;}}}void te11(){check();coutvv"箕冇大写字母ff«upper«ft个,小写字母"«lower«ff个,空格"vvspacevv”个,数字ff«numbervv”个,其他字符■•vvothervv”个”vvendl;}};int main(void){Str one;one.set();one.tel 1();system(ft pause ff);return 0;}(5)代码中要用到strlen函数,所以包含了string头文件,但strcmp函数在string中己经定义,所以下题屮改用Strcmpo#include <iostream>#include <string>using namespace std;#define SIZE 512class Str{private:char str1[SIZE];char str2[SIZE];■ nt i;public:void get(){cout«ft输入第一个字符串vvendl;OP+Q(Q+r1\■cout«M输入菊二个字符串:“vvendl; gets(str2);}void fun(){ Strcmp(str1, str2);}void Strcmp(char *m, char *n){int num;for(i=0; i<strlen(str1) || i<strlen(str2); i++){if(str1[i]==str2[i]){num = 0;}else{num = str1[i] - str2[i]; break;}}}};irrt main(void){Str one;one.get();one・fun();system(fl pause f,); return 0;}(6)注意:原有数组是不变的,但指针数组是排序Z后的。
西安交通大学实验报告课程__计算机程序设计__实验名称__指针与函数__第 1 页共 25 页系别____ _______ 实验日期 2014 年 4月 18日专业班级__ ____组别_____________ 实验报告日期 2014 年 4 月 19日姓名___ _______学号_ _报告退发 ( 订正、重做 )同组人_________________________________ 教师审批签字一、实验目的学会使用递归函数和函数重载,进一步熟练动态分配等指针使用方法。
二、实验内容(一)第一题:1、(必做题)使用递归算法编写如下程序:对于任意给定的实数 X 和整数k( k>0) ,计算 Xk 。
1.源程序代码:#include<iostream>using namespace std;double yunsuan(double x,int k);//递归函数用于计算x^kint main(){double x;int k;cout<<"请输入实数x:";cin>>x;cout<<"请输入正整数k:";cin>>k;while(k<=0)//判断输入的k是否满足要求,若否则提示输入错误并重新输入{cout<<"您的输入有误!请输入正整数:";cin>>k;}cout<<"计算结果是:"<<x<<"^"<<k<<"="<<yunsuan(x,k)<<endl;//输出运算结果return 0;}double yunsuan(double x,int k){if(k==1)//k=1时不再进行循环,输出值为xreturn x;else{double s=x*yunsuan(x,k-1);//对于k大于1的情况,进入下一循环return s;}}2.实验结果:(1)输入X正实数:(2)输入X正整数:(3)输入x为负数:(4)输入k为负数:3.问题分析:该函数的循环方式是:x^k=x*x^(k-1).设f(x,k)=x^k,那么就有f(x,k)=f(x,k-1)*x.而其结束递归的条件是k=1,此时有f(x,1)=x,由此给出初值。
(二)第二题:使用递归算法编写求斐波那契数列的第 n 项的函数,并编出主函数进行验证。
1.源程序代码:#include<iostream>using namespace std;int fib(int n) //递归函数,计算斐波那契数列的第n项{if(n==0)//对于n=0不再进行递归,返回值0return 0;else{if(n==1)return 1;//对于n=1不再进行递归,返回值1else{int s=fib(n-1)+fib(n-2);//将计算第n项归为计算第n-1和n-2项return s;}}}int main(){int n;cout<<"请输入要计算的项数(非负整数):";//提示输入项数,首项为第0项cin>>n;while(n<0)//对于不符合要求的输入值重新输入{cout<<"输入有误,请输入非负整数:";cin>>n;}cout<<"计算结果是:fib["<<n<<"]="<<fib(n)<<endl;//输出计算结果return 0;}2.实验结果:(1)输入项数正确(0或正整数):(2)输入项数有误(负数):3.问题分析:该题的递归方式:第n项为之前两项之和,即:fib(n)=fib(n-1)+fib(n-2),由此递归至fib(1)和fib(2)时结束递归,而fib(1)和fib(2)已知。
(三)第三题:重载判断两个数值大小的函数max ,这些数值可能是整型数、实型数和字符型,函数的返回值为两个数值中的最大值。
1.源程序代码:#include<iostream>using namespace std;double zhuanhuan(char *c)//为了避免语句的重复,将字符与数值转换部分作为函数{int i=0;double x=0;if(c[0]=='-'||c[0]=='+')//若首字符为…-‟或者…+‟则跳过i++;while(c[i]!='\0'&&c[i]!='.')//对于整数部分逐位累加,直至遇到小数点或者数字结束{x=x*10+(c[i]-'0');i++;}if(c[i]=='.')//对于小数部分进行累加{double s;//s用来反映数字所在位置是小数点后第几位,就用该数乘以的负几次方(s)i++;//从小数点后的一位开始循环for(s=0.1;c[i]!='\0';i++){x=x+s*(c[i]-'0');s=s/10;}}if(c[0]=='-')//若为负数,则在上述计算基础上乘以-1得到最终值x=-x;return x;//返回x作为char c的对应的数值}int imax(int a,int b)//对整型数进行处理{if(a>=b)return a;return b;}double imax(double a,double b)//对实数进行处理{if(a>=b)return a;return b;}double imax(char *c,char *d)//对字符型进行处理{double x=zhuanhuan(c);double y=zhuanhuan(d);return (x>=y?x:y);}int main(){int n;cout<<"请选择您要输入的数的类型,\n如果是整型请输入,实数型输入,字符型输入:";cin>>n;while(n!=1&&n!=2&&n!=3){cout<<"输入有误!重新选择:";cin>>n;}int a[2];double b[2];char c[12],d[12];if(n==1)//处理整型数{cout<<"请输入两个数:";cin>>a[0]>>a[1];cout<<"最大值为:"<<imax(a[0],a[1]);}else{if(n==2)//处理实数{cout<<"请输入两个数:";cin>>b[0]>>b[1];cout<<"最大值为:"<<imax(b[0],b[1]);}else//处理字符型{cout<<"请输入第一个数:";cin>>c;cout<<"请输入第二个数:";cin>>d;cout<<"最大值为:"<<imax(c,d);}}cout<<endl;return 0;}2.实验结果:(1)输入整数型:(2)输入为实数:(3)输入为字符:正数:(带正号):(不带正号):整数:负数:3.问题分析:该题的重点在于字符型的处理。
在实验报告中,采取了两个数字逐个分开输入的方法,因而主要只需要判断开头是否为负号、中间是否有小数点并区别小数点前后处理方法的不同这几个问题。
如果能够一次性输入两个数中间用空格隔开的话,就需要判断空格的位置,然后对空格之后的部分再进行与前半部分相同的判断方法,显得更加麻烦。
对字符型的处理思路:首先判断首字符是不是“-”或者“+”,如果是的话,先跳过从第二个字符开始处理,在最终的结果中再乘以-1即可;然后对于接下来的整数部分进行累加,直到遇见小数点,若没有小数点则一直执行到字符结束;如果有小数点的话,对于小数点后的部分再进行累加得到结果。
四、第四题:编写一个函数,用于去掉字符串前面的空格,其原型为 : char *myltrim(char *string);其中参数 string 为字符串,返回值为指向 string 的指针。
1.源程序代码:#include<iostream>using namespace std;char *myltrim(char *string){int i=0,j=0;while(*(string+i)==' ')i++;do{*(string+j)=*(string+i);i++;j++;}while(*(string+i-1)!='\0');return string;}int main(){char string[41];cout<<"请输入字符串:";cin.get(string,40);cout<<"去掉开头的空格之后为:\n"<<myltrim(string)<<endl;return 0;}2.实验结果:为验证处理空格时仅是将开头处理而不处理中间空格:(1)中间无空格:(2)中间有空格:3.问题分析:曾经出现的问题:起初运行时发现,即使没有判断开头空格的程序,输出结果也是没有空格的,后来检查发现是输入语句没有写为cin.get导致空格不被录入。
五、第五题:用牛顿迭代法求任意一元方程:anXn+an-1Xn-1+......+a1X1+a0 = 0 的根。
提示:迭代公式:Xn+1 = Xn + f(Xn) / f'(Xn)结束迭代过程的条件为(|f(Xn+1)|<ε)与(|Xn+1 - Xn|<ε)同时成立,其中ε为预先给定的精度要求。
1.源程序代码:#include<iostream>using namespace std;double cf(double x,int k)//乘方函数,输出结果为x的k次方{double s=1;while(k>0){s=s*x;k--;}return s;}double f(int n,double *a,double x)//计算函数值f(x)的函数{double sum=0;for(int i=0;i<n;i++){sum=sum+(*(a+i))*cf(x,i);}return sum;}double f_(int n,double *a,double x)//求导f_(x)函数{double sum=0;for(int i=1;i<n;i++){sum=sum+(*(a+i))*i*cf(x,i-1);}return sum;}double result(int n,double *a,double x) //求根函数{double u=0.00000001;//给定精确度double m;//设m为中间变量储存x,以便于进行循环条件的判断do{m=x;x=x-(f(n,a,x)/f_(n,a,x));}while(f(n,a,x)>=u||f(n,a,x)<=-u||x-m>=u||x-m<=-u);//循环直到达到精度return x;//返回最终计算结果}int main(){int n,i;cout<<"请输入最高项次数:";cin>>n;double *a=new double[n+1];//申请数组空间cout<<"请从低到高输入系数:";for(i=0;i<n+1;i++)cin>>*(a+i);double x=0;cout<<"计算结果为:"<<result(n+1,a,x)<<endl;delete a;//释放数组空间return 0;}2.实验结果:3.问题分析:思路分析:程序中用到的多个函数:乘方函数、计算f(x)、f_(x)的函数、自定义的求根的主体的函数、主函数。