C++ Primer Plus 编程练习题 第六章 分支语句和逻辑运算符
1.大小写转换
使用cctype库里的函数进行大小写转换,但要注意使用toupper或tolower时要进行强制类型转换,否则会输出ASCII值
#include <iostream>
#include<cctype>
using namespace std;
int main()
{
cout << "请输入字符串(大小写转换将遇到@时结束):\n";
char ch;
char res;
cin.get(ch);
while (ch != '@')
{
if (islower(ch))
cout<<(char) toupper(ch);
else if (isupper(ch))
cout<<(char)tolower(ch);
cin.get(ch);
}
return 0;
}
2.平均值比较
重点在于前面读取num时的处理,当读取类型为数字时并且count<10时读取
#include <iostream>
#include<array>
#include<cctype>
using namespace std;
int main()
{
const int Arsize = 10;
array<double, Arsize>donation;
cout << "您最多可以输入10个数字,在遇到非数字输入时将结束:\n";
double num;
int count = 0;
double sum = 0;
int res = 0;
while (cin >> num && count<Arsize)
{
donation[count] = num;
sum += num;
count += 1;
}
double ave;
ave = sum / count;
int i = 0;
while (i <count)
{
if (donation[i] > ave)
res += 1;
i++;
}
cout << "输入数字大于平均值的个数为" << res<<'\n';
cout << "输入数字平均值为" << ave;
return 0;
}