C++程序设计,课程代码4737,课后习题1答案

2018年2月4日18:39:38 发表评论 581 views

习题1

一、单项选择题

  1. 下列选项中不是C++语言关键字的是(B)。
    A. typedef  B. mycase  C. typeid  D. typename
  2. 下列选项中不是C++语言合法标识符的是(C)。
    A. area  B. _age  C. -xy  D. w123
  3. 下列选项中正确的标识符是(C)。
    A. case  B. de。fault  C. c_ase  D. a.b

二、填空题

  1. 用来处理标准输入的是 cin ,用来处理屏幕输出的是 cout 。
  2. 动态分配内存使用关键字 new ,释放内存使用关键字 delete 。
  3. 为整数55分配一块内存的语句为 new int[1] 。

 

三、改错题

  1. 分析如下主程序中的错误。
void main() {
    //int num;
    int& ref = num;
    ref = ref + 100;
    num = num + 50;
}

答:变量num没有声明。
2. 分析如下主程序中的错误。

void main() {
    int x = 58, y = 98;
    const int *p = &x;
    y = *p;
    *p = 65;
    p = &y;
}

答:code:5: error:只读变量不可更改。
3. 分析如下主程序中的错误。

void main() {
    int x = 58, y = 98, z = 55;
    int* const p = &x;
    *p = 65;
    p = &y;
    z = *p;
}

答:code:5: error:常量指针不可更改。

 

四、编程题

  1. 分别用字符和ASCII码形式输出整数值65和66。
#include <iostream>
using namespace std;
int main()
{
    int a= 65, b= 66;
    cout << (char)a<< "," << (char)b<< endl;
    cout << a<< "," << b<< endl;
}
  1. 编写一个为int型变量分配100个整形量空间的程序。
#include <iostream>
using namespace std;
int main()
{
    int *p= new int[100];
    delete []p;
    return 0;
}

3.编写完整的程序,它读入15个float值,用指针把它们存放在一个存储块里,然后输出这些值的和以及最小值。

#include <iostream>
using namespace std;
int main(){
	float *p = new float[15];
	float sum = 0.0f,min = 100.0f;	
	for(int i=0;i<15;i++){
		cout << "请输入第" << i+1 << "个值" ;
		cin >> *(p+i);
		cout << endl;
		sum = sum + *(p+i);
		if(*(p+i)<min){
			min = *(p+i);
		}
	}
	cout << "sum=" << sum << endl;
	cout << "min=" << min << endl;
	delete []p;
}

 

4.声明如下数组:

int a[] = {1, 2, 3, 4, 5, 6, 7, 8};

先查找4的位置,将数组a复制给数组b,然后将数组a的内容反转,再查找4的位置,最后分别输出数组a和b的内容。

#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
using namespace std;

int main(){
	int a[] = {1,2,3,4,5,6,7,8};
	int b[8];
	//查找4的位置
	int *p = find(a,a+8,4);
	if(p == a+8){
		cout << "没有值为4的数组元素" << endl;
	}else{
		cout << *p << endl;
	}
	//将数组a复制给数组b
	copy(a,a+8,b);
	//数组a的内容反转
	reverse(a,a+8);
	//在查找4的位子
	p = find(a,a+8,4);
	if(p == a+8){
		cout << "没有值为4的数组元素" << endl;
	}else{
		cout << *p << endl;
	}
	//分别输出a和b的内容
	copy(a,a+8,ostream_iterator<int>(cout,","));
	cout << endl;
	copy(b,b+8,ostream_iterator<int>(cout,","));
	cout << endl;
}

 

 

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: