C++学习——第6章 数组和字符串(上)

1. 使用一个整数数组计算一组人的平均身高,再计算出有多少人的身高超过平均身高。

#include <iostream>
#include <cctype>

using namespace std;

int main()
{
	int height[10];
	int count = 0;
	char reply = 0;

	//用户输入及输入完毕与否,并判断数组容量到达最大与否
	do{
		cout << endl
			 << "Enter a height as an integral number of inches: ";
		cin >> height[count++];

		cout << "Do you want to enter another (y or n)? ";
		cin >> reply;
	} while(count < 10 && tolower(reply) == 'y');

	if(count == 10)
		cout << endl << "Maximum height count reached." << endl;


	//求数组平均数
	double average = 0.0;
	for (int i=0; i<count; i++)
		average += height[i];
	average /= count;
	cout << endl
		 << "Average height is " << average << " inches."
		 << endl;

	
	//判断数组中超过平均值的数量
	int above_average=0;
	for (int j=0; j<count; j++)
		if(height[j] > average)
			above_average++;

	//输出
	cout << "there "
		 << (above_average == 1 ? "is " : "are ")
		 << above_average << " height"
		 << (above_average == 1 ? " " : "s ")
		 << "above average."
		 << endl;
	return 0;

}



2.   sizeof()运算符可以提供变量占用的字节数,那么就利用它可以求出数组中元素的个数,其中,表达式sizeof values会计算出整个数组占用的字节数。而表达式sizeof values[0]则会计算出一个元素占用的字节数。两者相除就能得到数组元素个数。代码如下:

#include <iostream>
using namespace std;

int main()
{
	int values[]={2,3,5,7,11,13,17,19,23,29};

	//利用sizeof求数组元素个数
	cout << endl
		 << "There are "
		 << sizeof values/ sizeof values[0]
		 << " elements in the array. "
		 << endl;
	
	//求数组元素之和,for循环灵活运用
	int sum=0;
	for (int i=0; i<sizeof values / sizeof values[0]; sum += values[i++]);

	cout << "The sum of the array elements is " << sum
		 << endl;

	return 0;
}




3.  计算元音字母与辅音字母数量,代码中,在text数组中存储输入内容。但是,不能使用通常方法获取输入,即不能使用提取运算符(>>),因为它,即cin >> text;只能读到一个空格为止,比如我输入hello world!,计算机只能读到hello就截止了,因为提取运算符把空格看做是输入值之间的分隔符,所以不能读取包含空格的整个字符串。(包括\n都会被看做是分隔符,因此不能使用它表示字符串的结尾),所以我们使用另一种方法,cin.getlin( text, maxlength);cin流的getline()函数读取并存储一整行字符,包括空格,在读取了换行符‘\n’(即按下回车)后输入结束。代码如下:

#include <iostream>
#include <string>
using namespace std;

int main()
{
	const int maxlength = 100;
	char text[maxlength] = {0};

	cout << endl << " enter a line of text: " << endl;

	cin.getline(text, maxlength);	//cin流的getline()函数读取并存储一整行字符,包括空格

	cout << "You entered: " << endl << text << endl;

	
	//计算元音字母数与辅音字母数,循环嵌套的方式灵活计算出来
	int vowels=0;
	int consonants=0;
	for (int i=0; text[i] != '\0'; i++)
		if(isalpha(text[i]))
			switch(tolower(text[i]))
		{
			case 'a': case 'e': case 'i':
			case 'o': case 'u':
				vowels++;
			break;
			default:
				consonants++;
		}
	
	//输出
	cout << "Your input contained"
		 << vowels	<< " vowels and "
		 << consonants << " consonants. "
		 << endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值