C++程序设计基本编程题型全解 联系客服

发布时间 : 星期三 文章C++程序设计基本编程题型全解更新完毕开始阅读426d2671856a561252d36fe7

其中s=(a+b+c)/2。设计一个函数求三角形的面积。 #include #include

bool triangle(float a,float b,float c); double area(float a,float b,float c); void main(void) { float a,b,c; cout<<\请输入三角形的边a:\ cin>>a; cout<<\请输入三角形的边b:\ cin>>b; cout<<\请输入三角形的边c:\ cin>>c; while(!triangle(a,b,c)) { cout<<\不满足三角形的定义\

cout<<\请输入三角形的边a:\ cin>>a; cout<<\请输入三角形的边b:\ cin>>b; cout<<\请输入三角形的边c:\ cin>>c; } cout<<\该三角形的面积为:\}

double area(float a,float b,float c)//面积公式 { double area; float s=(a+b+c)/2; area=sqrt(s*(s-a)*(s-b)*(s-c)); return area; }

bool triangle(float a,float b,float c)//是否是三角形 { if(a<=0 || b<=0 || c<=0)return false; if(a+b<=c || a+c<=b || b+c<=a)return false; return true; }

第六单元 数组

根据题目要求,编写完整程序加以验证,可调用已有函数,也可添加其它函数 (1)编写一个函数:bool isSorted(const int a[], int n),判断数组a中的元素是否按升序排列。

#include

bool isSorted(const int a[],int n) { for(int i=1;i<=n-1;i++) { if(a[i]

void main() { int a[10]={1,2,2,4,5,6,7,8,9,10}; if(isSorted(a,10)==true) cout<<\按升序排列\\n\ else cout<<\非升序排列\\n\}

(2)编写一个函数:void getRandom(int a[], int n),生成0到100之间的随机整数作为数组元素。再编写一个函数int getMax(const int a[], int n),在数组a中找出最大值并返回下标。再编写一个排序函数,将int数组进行升序排序,运行程序并验证正确性。

#include #include #include

void getRandom(int a[],int n); int getMax(const int a[],int n); void sort(int a[],int n);

const int n = 100; //the length of the array void main() { int a[n],counter = 0; getRandom(a,n); //create random array

cout<<\original array is:\ //show original array

for(int i = 0;i < n;i++) { cout<

numbers in array

{ if(a[i] == a[getMax(a,n)]) cout<<\\max num in array is \

}

cout<<\ sort(a,n); //sort the array

cout<<\ array

for(i = 0;i < n;i++) { cout<

void getRandom(int a[],int n) { srand((unsigned)time(NULL)); the current time

for(int i = 0;i < n;i++) a[i] = rand() % 101; }

int getMax(const int a[],int n) { int max_subscript = 0; for(int i = 1;i < n;i++) { if(a[max_subscript] < a[i]) max_subscript = i; } return(max_subscript); }

void sort(int a[],int n) { int i, j, temp; for(i = 0; i < n-1; i++) for(j = 0; j < n-1-i; j++) if(a[j] > a[j+1]) { temp =a[j];

//show the sorted //the seed is //the bubblesort a[j] = a[j+1]; a[j+1] = temp; }; }

(3)编写一个函数:bool insertSort(int a[], int maxnum, int n, int x),形参a是一个数组,形参maxnum是数组a的大小,即能容纳最多元素个数,n是当前已插入的元素个数,形参x是要插入的一个值。该函数尝试将x插入到数组a中的合适位置,使所有元素保持升序排列。如果成功插入,返回true。如果没有位置插入(即已满),就返回false。验证该函数的正确性。

#include #include #include

bool insertSort(int a[], int maxnum, int n, int x) { if (n==maxnum) return false; for (int i=0;ii;j--)//i及i后的所有值往后移一个位置 a[j]=a[j-1]; a[i]=x; return true; } } a[i]=x; return true; }

void print(int a[],int maxnum) { cout<<\数组打印:\\n\ for(int i=0;i

void main() { int a[10];//数组定义并初始化为0 int maxnum=10; int n=0;//当前已插入个数为0 bool result;