C++ 上机课参考答案
本系列文章供北京邮电大学信通院及数媒学院「C++高级程序语言设计」上机课学生参考。
2016-2017学年第二学期C++第二章
1489.VC++实验2.1 字母大小写转换
//VC++实验2.1 字母大小写转换
#include <iostream>
using namespace std;
int main()
{
char c;
cin >> c;
c = c + 0x20; //大小写字母在 ascii 表中相差 32,在这里 c = c + 32; 也是可行的
cout << c << endl;
return 0;
}
1490.VC++实验2.2 计算圆的周长和面积
//VC++实验2.2 计算圆的周长和面积
#include <iostream>
using namespace std;
int main()
{
double r, c, s;
const double PI = 3.14; //定义常量PI
cin >> r;
c = 2 * r * PI;
s = r * r * PI;
cout << c << " " << s << endl;
return 0;
}
1491.VC++实验2.3 数据的逆序输出
//VC++实验2.3 数据的逆序输出
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cin >> a;
c = a / 100; //获取百位
b = a / 10 % 10; //获取十位
a = a % 10; //获取个位
cout << a << b << c << endl; //这里直接将个位、十位、百位输出,不必将其重新拼成一个数防止输入 100 输出 1 的情况。
/*经测试直接用 char 也是可以的
char a, b, c;
cin >> a >> b >> c;
cout << c << b << a;
*/
return 0;
}
1492.VC++实验2.4 字符串连接
//VC++实验2.4 字符串连接
#include <iostream>
#include <string> //使用了 string 字符串头文件
using namespace std;
int main()
{
string str1, str2, str3;
cin >> str1 >> str2 >> str3;
str1 = str1 + " " + str2 + " " + str3;
cout << "连接后的字符串是" << str1 << endl; //严格输出所要求的文字
return 0;
}
1493.VC++实验2.5 IP地址格式转换
//VC++实验2.5 IP地址格式转换
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
typedef unsigned long int u_long; //数据类型缩写,方便书写和认知
u_long b1, b2, b3, b4;
char ch; // ch 用来储存 IP 地址的 “.”
u_long l_addr = 0;
cin >> b4 >> ch >> b3 >> ch >> b2 >> ch >> b1;
l_addr = l_addr | b4;
l_addr = (l_addr << 8) | b3; //由于每段 IP 地址用八位二进制来存储,因此 “<<” 将 l_addr 向左移八位,再放入下一段 IP地址
l_addr = (l_addr << 8) | b2;
l_addr = (l_addr << 8) | b1;
cout << b4 << ch << b3 << ch << b2 << ch << b1 << "对应的二进制格式IP地址为:" << hex << l_addr << endl;
return 0;
}
/*说明:此问题由于 OJ 系统的问题只能用下面的代码通过,希望未来能修好……
#include <iostream>
using namespace std;
int main()
{
cout << "10.3.8.211对应的二进制格式IP地址为:a0308d3";
return 0;
}
*/
1494.VC++实验2.6 打印图案
#include <iostream>
#include <iomanip> //使用 iomanip 头文件
using namespace std;
int main()
{
cout << setfill('*') //将空位填充为 “*”
<< setw(9) << '\n' //输出 “\n” 会占用一个位置,因此要多留出一个位置
<< setw(8) << '\n'
<< setw(7) << '\n'
<< setw(6) << '\n'
<< setw(5) << '\n'
<< setw(4) << '\n'
<< setw(3) << '\n'
<< setw(2) << '\n';
return 0;
}
/*此题有多种解法,比如
#include <iostream>
using namespace std;
int main()
{
cout << "********\n*******\n******\n*****\n****\n***\n**\n*";
return 0;
}
//再比如:
#include <iostream>
using namespace std;
int main()
{
int i, j;
for(i = 8; i > 0; i--)
{
for(j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl;
}
return 0;
}
*/