南大C++:《程序设计教程 用C++语言编写》答案(一)
这些是我自己写的代码,全部通过编译。
3.8.1 编写一个程序,将华氏温度转换为摄氏温度。
/*
P67 3.8.1
编写一个程序,将华氏温度转换为摄氏温度。
*/
#include <iostream>
using namespace std;
int main()
{
int f, c;
cin >> f;
c = 5 * (f - 32) / 9;
cout << c << endl;
}
3.8.2 编写一个程序,将用24小时制表示的时间转换为12小时表示的时间。
/*
P67 3.8.2
编写一个程序,将用24小时制表示的时间转换为12小时表示的时间。
*/
#include <iostream>
using namespace std;
int main()
{
int h, m;
char ap;
while (1){
cout << "hour:";
cin >> h;
cout << "minute:";
cin >> m;
if (h < 13)
ap = 'a';
else
{
h -= 12;
ap = 'p';
}
cout << h << ':' << m << ap << 'm' << endl;
}
}
3.8.3 编写一个程序,分别按正向和逆向输出小写字母a-z。
/*
P67 3.8.3
编写一个程序,分别按正向和逆向输出小写字母a-z。
*/
#include <iostream>
using namespace std;
int main()
{
for (int i = 'a'; i <= 'z'; i++)
cout << (char)i << ' ';
cout << endl;
for (int i = 'z'; i >= 'a'; i--)
cout << (char)i << ' ';
cout << endl;
}
3.8.4 编写一个程序,从键盘输入一个正整数,判断该正整数为几位数,并输出其位数。
/*
P67 3.8.4
编写一个程序,从键盘输入一个正整数,判断该正整数为几位数,并输出其位数。
*/
#include <iostream>
using namespace std;
int main()
{
int a;
while (cin >> a)
{
int i=0;
while (a)
{
a = a / 10;
i++;
}
cout << i << endl;
}
}
3.8.5 编写一个程序,对输入的一个算术表达式(以字符‘#’结束),检查圆括号配对情况。输出:配对,多左括号或多右括号。
/*
P67 3.8.5
编写一个程序,对输入的一个算术表达式(以字符‘#’结束),检查圆括号配对情况。输出:配对,多左括号或多右括号。
*/
#include <iostream>
using namespace std;
int main()
{
char s[100];
while (cin >> s)
{
int count = 0;
int i = 0;
while (s[i] != '#')
{
if (s[i] == '(')
count++;
if (s[i] == ')')
count--;
i++;
}
if (count == 0)
cout << "配对" << endl;
else if (count < 0)
cout << "多右括号" << endl;
else
cout << "多左括号" << endl;
}
}