C++ Primer Plus 第二章编程练习

简介: C++ Primer Plus 第二章编程练习

1.编写一个C++程序,它显示您的姓名和地址。

#include<iostream>
using namespace std;
int main() 
{
  cout << "My name is ZhiqiangHo" << endl;
  cout << "My sddress is Shengyang" << endl;
  return 0;
}

2.编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(一long等于220码)。

#include<iostream>
using namespace std;
int changema(int);
int main()
{
  cout << "Please input long:" << endl;
  int a;
  cin >> a;
  cout << "Change to Ma is:" << changema(a) << endl;
  return 0;
}
int changema(int b)
{
  return b * 120;
}

3.编写一个C++程序,它使用3个用户定义的函数(包含main()),并生成下面的输出:

Three blind mice

Three blind mice

See how they run

See how they run

其中一个函数要调用两次,该函数生成前两行;另一个函数也被调用两次,并生成其余的输出。

#include<iostream>;
using namespace std;
void firstout(void);
void second(void);
int main()
{
  firstout();
  firstout();
  second();
  second();
  return 0;
}
void firstout(void)
{
  cout << "Three blind mice" << endl;
}
void second(void)
{
  cout << "See How they run" << endl;
}

4. 编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月,如下所示:

Enter you age : 29

#include<iostream>;
using namespace std;
int change(int);
int main()
{
  cout << "Please input you age:" << endl;
  int age;
  cin >> age;
  cout << "Your age Have" << change(age) << "mounth" << endl;
  return 0;
}
int change(int age)
{
  return age * 12;
}

5.编写一个程序,其中的main()调用一个用户定义的函数(以摄氏温度为参数,并返回相应的华氏温度)。该程序按下面的格式要求用户输入摄氏温度值,并显示结果:

Please enter a Celeius value : 20

20 degree Celsius is 68 degrees Fahrenheit.

下面是转换公式:

华氏温度 = 1.8 * 摄氏温度 + 32.0

#include<iostream>;
using namespace std;
int change(int);
int main()
{
  cout << "Please enter a Celsius value:" << endl;
  int shewendu;
  cin >> shewendu;
  cout << shewendu <<"degrees Celsius is" << change(shewendu) << "degrees fahrenheit" << endl;
  return 0;
}
int change(int shewendu)
{
  return shewendu * 1.8 + 32;
}

后面的都一个类型,不写了。

6.编写一个程序,其main()调用一个用户定义的函数(以光年为基础,并返回对应天文单位的值)。该程序按下面的格式要求用户输入光年值,并显示结果

Enter the number of light years: 4.2

4.2 light years = 265608 astronomical units

天文单位是从地球到太阳的平均距离(约150000000公里或93000000英里),光年是光一年走的距离(约10万亿公里或6万亿英里)(除太阳外,最近的恒星大约离地球4.2光年)。请使用double类型,转换公式为:

1光年=63240天文单位。

7.编写一个程序,要求用户输入小时数和分时数。在main()函数中,将这两个值传递给一个void函数,后者以下面这样的格式显示这两个值

Enter the number of hours:9

Enter the number of minutes : 28

Time: 9:28

相关文章
|
5天前
|
算法 编译器 C语言
探索C++编程的奥秘与魅力
探索C++编程的奥秘与魅力
|
5天前
|
编译器 C语言 C++
C语言,C++编程软件比较(推荐的编程软件)
C语言,C++编程软件比较(推荐的编程软件)
|
1天前
|
算法 程序员 C语言
C++:深度探索与编程实践
C++:深度探索与编程实践
10 3
|
6天前
|
编译器 程序员 C++
C++从入门到精通:3.1模板编程——提高代码的复用性和灵活性
C++从入门到精通:3.1模板编程——提高代码的复用性和灵活性
|
6天前
|
C++
C++从入门到精通:2.1.2函数和类——深入学习面向对象的编程基础
C++从入门到精通:2.1.2函数和类——深入学习面向对象的编程基础
|
7天前
|
存储 编译器 对象存储
【C++基础(十)】C++泛型编程--模板初阶
【C++基础(十)】C++泛型编程--模板初阶
【C++基础(十)】C++泛型编程--模板初阶
|
13天前
|
编译器 C++
C++编程之美:探索初始化之源、静态之恒、友情之桥与匿名之韵
C++编程之美:探索初始化之源、静态之恒、友情之桥与匿名之韵
21 0
|
1天前
|
存储 Java C++
【C++类和对象】探索static成员、友元以及内部类
【C++类和对象】探索static成员、友元以及内部类
|
1天前
|
安全 程序员 编译器
【C++类和对象】初始化列表与隐式类型转换
【C++类和对象】初始化列表与隐式类型转换
|
1天前
|
安全 编译器 C++
【C++类和对象】const成员函数及流插入提取
【C++类和对象】const成员函数及流插入提取