第五章 循环 程序设计练习

5.1(统计正数和负数的数目,计算平均值)编写程序,读入整数(数目未定),判定读入的整数中有多少正数,多少负数,并计算这些整数的总和与平均值(0不计算在内)。如果读入0,程序即终止。平均值以浮点数显示。

#include <iostream>
using namespace std;

int main()
{
	int numberOfPositives = 0;//正数的数目
	int numberOfNegatives = 0;//负数的数目
	int total = 0;//所有整数的和
	double average = 0;//所有整数的平均值
	int digit;//用户输入的数字

	//提示用户输入一行整数
	cout << "Enter an integer ,the input ends if it is 0:";
	do
	{
		cin >> digit;
		if (digit > 0)//如果输入大于0为正数
			numberOfPositives++;//正数数目加一
		else if (digit < 0)//如果输入小于0为负数
			numberOfNegatives++;//负数数目加一
		total += digit;//把每次输入的数都加到总和中
	} while (digit);//如果输入是0停止循环

	//如果正数负数的数目都为0,证明没有输入,输出提示信息
	if (numberOfNegatives == 0 && numberOfPositives == 0)
	{
		cout << "No number are entered except 0" << endl;
		return 0;//直接结束函数,不再进行运算
	}

	//计算平均值=总和/总数,总数=(正数个数+负数个数)
	average = total / ((double)numberOfNegatives + numberOfPositives);
	//输出
	cout << "The number of positives is " << numberOfPositives << endl;
	cout << "The number of negatives is " << numberOfNegatives << endl;
	cout << "The total is " << total << endl;
	cout << "The average is " << average << endl;

	return 0;
}

5.2(重复加法练习)程序清单5-4生成10个随机的减法题。修改程序,使之能生成10个随机的加法题,要求两个运算数是1~15之间的整数。显示回答正确的题数和测试所用的时间。

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	int correctCount = 0;//答对题目的数量
	int count = 0;//答题的数目
	long startTime = time(0);//答题开始时间
	const int NUMBER_OF_QUESTIONS = 15;//系统默认的每次答题个数
	
	srand(time(0));//设置随机种子

	while (count < NUMBER_OF_QUESTIONS)
	{
		//生成两个随机数
		int number1 = rand() % 15;
		int number2 = rand() % 15;
		//输出两个数相加的提示信息
		cout << "What is " << number1 << " + " << number2 << " ?";
		int answer;
		cin >> answer;//用户输入答案

		//判断输入是否正确
		if (answer == (number1 + number2))
		{
			cout << "You are correct!\n\n";
			correctCount++;
		}
		else
		{
			cout << "Your answer is wrong.\n" << number1 << " + " << number2
				<< " shoule be " << number1 + number2 << "\n" << endl;
		}
		//答题数目加一
		count++;
	}

	long endTime = time(0);//答题结束时间
	long testTime = endTime - startTime;//总答题时间=开始时间-结束时间
	//输出
	cout << "\nCorrect count is " << correctCount << "\nTest time is " << testTime << " seconds\n" << endl;

	return 0;
}

5.3(将千克数转换为磅数)编写程序,输出下表(注意1千克等于2.2磅)

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

int main()
{
	const double KILOGRAMS_TO_POUNDS = 2.2;

	cout << left;//设置输出左对齐
	cout << setw(10) << "Kilograms" << "\t" << "Pounds" << endl;
	for (int i = 1; i < 200; i++)
	{
		cout << left;
		cout << setw(10) << i << "\t" << i * KILOGRAMS_TO_POUNDS << endl;
	}

	return 0;
}

5.4(将英里数转换为千米数)编写程序,输出下表(注意1英里等于1.609千米)

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

int main()
{
	const double MILES_TO_KILOMETERS = 1.609;

	cout << left;//设置输出左对齐
	cout << setw(10) << "Miles" << "\t" << "Kilometers" << endl;
	for (int i = 1; i < 11; i++)
	{
		cout << left;
		cout << setw(10) << i << "\t" << fixed << setprecision(3) << i * MILES_TO_KILOMETERS << endl;
	}

	return 0;
}

5.5(将千克数转换为磅数,将磅数转换为千克数)编写程序,显示下面两个并排的表(注意1千克等于2.2磅)。

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

int main()
{
	const double KILOGRAMS_TO_POUNDS = 2.2;

	cout << left;//设置输出左对齐
	cout << setw(10) << "Kilograms" << "\t" << "Pounds" << "\t|" << "\t" << "Pounds\t" << "Kilograms" << endl;
	for (int i = 1; i < 200; i += 2)
	{
		cout << left;
		cout << setw(10) << fixed << setprecision(2) << i << "\t" << i * KILOGRAMS_TO_POUNDS << "\t|" 
			<< "\t" << i * 2.5 + 17.5 << "\t" << (i * 2.5 + 17.5) / KILOGRAMS_TO_POUNDS << endl;
	}

	return 0;
}

5.6(将英里数转换为千米数,将千米数转换为英里数)编写程序,输出下面两个并排的表(注意1英里等于1.609千米)。

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

int main()
{
	const double MILES_TO_KILOMENTERS = 1.609;

	cout << left;//设置输出左对齐
	cout << setw(10) << "Miles" << "\t" << "Kilomenters" << "\t|" << "\t" << "Kilomenters\t" << "Miles" << endl;
	for (int i = 1; i < 11; i ++)
	{
		cout << left;
		cout << setw(10) << fixed << setprecision(3) << i << "\t" << i * MILES_TO_KILOMENTERS << "\t\t|"
			<< "\t" << i * 5 + 15 << "\t" << (i * 5 + 15) / MILES_TO_KILOMENTERS << endl;
	}

	return 0;
}

5.7(使用三角函数)输出下列表格,显示0~360度中以10度为单位增长的度数相应的sin值与cos值。精确到小数点后四位。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
	const double PI = 3.1416;
	cout << setw(10) << left << "Degree" << "\t" << "Sin" << "\t" << "Cos" << endl;
	for (int i = 0; i <= 360; i += 10)
	{
		cout << setw(10) << left << i << fixed << setprecision(4) << "\t" <<
			sin(i / 360.0 * 2 * PI) << "\t" << cos(i / 360.0 * 2 * PI) << endl;
	}

	return 0;
}

5.8(使用sqrt函数)使用sqrt函数编写程序来输出下列表格。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
	cout << setw(10) << left << "Number" << "\t" << "SquareRoot" << endl;
	for (int i = 0; i <= 20; i += 2)
	{
		cout << setw(10) << left << i << "\t" << fixed << setprecision(4) << sqrt(i) << endl;
	}

	return 0;
}

5.9(金融应用:计算未来的学费)假定一所大学今年的学费为10000美元,且以每年5%的幅度增长。编写一个程序,使用循环计算10年内的学费。编写另一个程序,计算10年内以每年为开始的四年大学的总学费。

//计算10年内的学费
#include <iostream>
using namespace std;

int main()
{
	const double BASED_TUITION = 10000;//基础学费
	const double RATE_OF_YEAR = 0.05;//每年的增长幅度

	double currentTuition = BASED_TUITION;
	for (int i = 1; i < 10; i++)
	{
		currentTuition *= (1.0 + RATE_OF_YEAR);
		cout << "从今年开始,往后第" << i << "年的学费为" << currentTuition << "美元" << endl;
	}

	return 0;
}
//计算往后10年,每四年的学费
#include <iostream>
using namespace std;

int main()
{
	const double BASED_TUITION = 10000;//基础学费
	const double RATE_OF_YEAR = 0.05;//每年的增长幅度

	double currentTuition = BASED_TUITION;//当前年份的学费(因为从第一年开始,所以初始值为基础学费BASED_TUITION)
	double totalTuition;//四年学费总额
	//第一层循环,现在是第几年
	for (int i = 1; i < 10; i++)
	{
		totalTuition = 0;//当前学费总额为清零
		currentTuition *= (1.0 + RATE_OF_YEAR);//第i年的学费
		double currentTuitionTemp = currentTuition;//将当前第i年的学费赋给临时变量,以供下面的for循环使用
		//第二层循环,在今年的基础上,计算总共四年的总和
		for (int j = 0; j < 4; j++)
		{
			totalTuition += currentTuitionTemp;
			currentTuitionTemp *= (1.0 + RATE_OF_YEAR);
		}
		cout << "从第" << i << "年开始,四年的总的学费为" << totalTuition << "美元" << endl;
	}

	return 0;
}

5.10(求最高成绩)编写一个程序,由用户输入学生数和每个学生的姓名及成绩,最终输出成绩最高的学生的姓名和成绩。

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

int main()
{
	int numberOfStudent;//学生数目
	string name;//考生姓名
	double score;//考试分数
	string maxName;//最高分的学生姓名
	double maxScore = 0.0;//最高分的学生分数

	cout << "请输入学生数:";
	cin >> numberOfStudent;

	for (int i = 0; i < numberOfStudent; i++)
	{
		cout << "\n请输入学生姓名:";
		cin >> name;
		cout << "\n请输入学生分数:";
		cin >> score;
		if (score > maxScore)
		{
			maxScore = score;
			maxName = name;
		}
	}
	cout << "\n成绩最高的学生姓名为:" << maxName << ",分数为:" << maxScore << endl;

	return 0;
}

5.11(求最高的两个成绩)编写一个程序,提示用户输入学生数和每个学生的姓名及成绩,程序输出最高成绩和成绩排在第二位的学生的姓名和成绩。

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

int main()
{
	int numberOfStudent;//学生数目
	string name;//考生姓名
	double score;//考试分数
	string firstName;//最高分的学生姓名
	double firstScore = 0.0;//最高分的学生分数
	string secondName;//成绩排第二位的学生姓名
	double secondScore = 0.0;//成绩排第二位的学生分数

	cout << "请输入学生数:";
	cin >> numberOfStudent;

	for (int i = 0; i < numberOfStudent; i++)
	{
		cout << "\n请输入学生姓名:";
		cin >> name;
		cout << "\n请输入学生分数:";
		cin >> score;
		if (score > firstScore)//如果本次输入大于当前最高分
		{
			secondName = firstName;//将当前的第一名变为第二名
			secondScore = firstScore;//将当前的最高分变为第二名的分数
			firstScore = score;//本次输入的分数为现有最高分
			firstName = name;//本次输入的姓名为现有最高分的姓名
		}
		else if (score > secondScore)//本次输入小于当前最高分,但大于第二名的分数
		{
			secondName = name;
			secondScore = score;
		}
	}
	cout << "\n成绩最高的学生姓名为:" << firstName << ",分数为:" << firstScore << endl;
	cout << "\n成绩第二的学生姓名为:" << secondName << ",分数为:" << secondScore << endl;

	return 0;
}

5.12(求同时能被5和6整除的数)编写程序,输出100~1000之间所有能同时被5和6整除的整数,每行输出10个。数字间由空格分开。

#include<iostream>
using namespace std;

int main()
{
	const int BEGIN_NUMBER = 100;//开始遍历的数字
	const int END_NUMBER = 1000;//结束遍历的数字
	const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行显示多少个数字

	int count = 0;//当前能同时整除5和6的整数的数量
	for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
	{
		if (i % 5 == 0 && i % 6 == 0)//判断是否能同时被5和6整除
		{
			cout << i << " ";//该数字能被5和6同时整除,输出此数字,用空格隔开
			count++;//当前整除的数量加一
			if (count % NUMBER_OF_PRIMES_PER_LINE == 0)//如果当前数量为10的整数,换行
				cout << endl;
		}
	}

	return 0;
}

5.13(求能被5/6之一整除的数)编写程序,输出100~200之间所有能被5和6之一整除的,且只被两者之一整除的整数,每行显示10个。数字间由空格分开。

#include<iostream>
using namespace std;

int main()
{
	const int BEGIN_NUMBER = 100;//开始遍历的数字
	const int END_NUMBER = 200;//结束遍历的数字
	const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行显示多少个数字

	int count = 0;//当前能只整除5或6的整数的数量
	for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
	{
		if ((i % 5 == 0 && i % 6 != 0) || (i % 5 != 0 && i % 6 == 0))//判断是否能被5和6之一且只被之一整除
		{
			cout << i << " ";//该数字能被5或6之一且只被之一整除,输出此数字,用空格隔开
			count++;//当前整除的数量加一
			if (count % NUMBER_OF_PRIMES_PER_LINE == 0)//如果当前数量为10的整数,换行
				cout << endl;
		}
	}

	return 0;
}

5.14(求满足n^2>12000的最小的n)使用一个while循环,求平方值大于12000的最小整数n。

#include <iostream>
using namespace std;

int main()
{
	const int SQUARED_VALVE = 12000;//平方值
	int n = 0;
	while (n * n <= SQUARED_VALVE)
		n++;
	cout << "平方值大于" << SQUARED_VALVE << "的最小整数n为:" << n;

	return 0;
}

5.15(求满足n^3<12000的最大的n)使用一个while循环,求立方值小于12000的最大整数n。

#include <iostream>
using namespace std;

int main()
{
	const int SQUARED_VALVE = 12000;//立方值
	int n = 0;
	while (n * n * n <= SQUARED_VALVE)//当前n的立方大于SQUARED_VALVE的时候跳出循环
		n++;
	cout << "平方值大于" << SQUARED_VALVE << "的最小整数n为:" << n - 1;//则n-1即为最大值

	return 0;
}

5.16(计算最大公约数)程序清单5-10之外的另一种求两个整数n1和n2的最大公约数的方法如下:首先求n1和n2中较小的那个值d,然后按顺序检查d、d-1、d-2、……、2或1是否能同时整除n1和n2.第一个检查到的公约数显然就是n1和n2的最大公约数。编写程序,提示用户输入两个正整数,输出最大公约数。

#include <iostream>
using namespace std;

int main()
{
	int firstInteger;//第一个整数
	int secondInteger;//第二个整数
	//提示用户输入第一个整数
	cout << "Enter first integer:";
	cin >> firstInteger;
	//提示用户输入第二个整数
	cout << "Enter second integer:";
	cin >> secondInteger;
	//循环遍历最大公约数,取两个整数中较小的赋值给i
	for (int i = firstInteger < secondInteger ? firstInteger : secondInteger; i > 0; i--)
	{
		//如果i能同时被两个整数整除,则i就是最大公约数,输出i,跳出循环
		if (secondInteger % i == 0 && firstInteger % i == 0)
		{
			cout << "The greaat common divisor for " << firstInteger << " and " << secondInteger << " is " << i << endl;
			break;
		}
	}
	return 0;
}

5.17(输出ASCII字符表)编写一个程序,打印ASCII字符表中从!到~之间的字符,每行打印10个字符。ASCII表在附录B中显示。字符由空格分开。

#include <iostream>
using namespace std;

int main()
{
	const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行显示多少个数字

	for (char i = '!'; i <= '~'; i++)
	{
		if ((i - '!') % NUMBER_OF_PRIMES_PER_LINE == 0)
			cout << endl;
		cout << i << " ";
	}

	return 0;
}

5.18(求一个整数的因子)编写一个程序,读入一个整数,由小至大显示其所有因子。例如,如果输入整数为120,输出应该是:2、2、2、3、5。

#include <iostream>
using namespace std;

int main()
{
	int number;//用户输入的整数
	cout << "请输入一个整数:";
	cin >> number;
	//从2开始循环到小于number
	for (int i = 2; i <= number; i++)
	{
		//如果i能被number整除
		if (number % i == 0)
		{
			cout << i << " ";//i就是number的因子
			number /= i;//number此时已提取出一个因子,将number的值除以该因子,得到新的number值
			i = 1;//将i的值置为1(因为for中有i++,置为1,i++以后就变为了2,还是从2开始循环的),继续新number的循环,提取因子
		}
	}

	return 0;
}

5.19(输出金字塔)编写程序,提示用户输入1~15中的某个数字,输出金字塔图案。

#include <iostream>
using namespace std;

int main()
{
	int numberOfLine;
	cout << "Enter the number of lines:";
	cin >> numberOfLine;

	for (int i = 1; i <= numberOfLine; i++)
	{
		for (int j = numberOfLine; j >= i; j--)
			cout << "\t";
		for (int k = i; k >= 1; k--)
			cout << k << "\t";
		for (int k = 2; k <= i; k++)
			cout << k << "\t";
		cout << endl;
	}

	return 0;
}

5.20(用循环打印4个图案)使用嵌套循环编写4个程序,分别输出下面四个图形。

#include <iostream>
using namespace std;

int main()
{
	//Pattern A
	cout << "Pattern A" << endl;
	for (int i = 1; i <= 6; i++)
	{
		for (int j = 1; j <= i; j++)
			cout << j << "\t";
		cout << endl;
	}

	cout << "Pattern B" << endl;
	//Pattern B
	for (int i = 1; i <= 6; i++)
	{
		for (int j = 1; j <= 6 - i + 1; j++)
			cout << j << "\t";
		cout << endl;
	}

	cout << "Pattern C" << endl;
	//Pattern C
	for (int i = 1; i <= 6; i++)
	{
		for (int j = i; j >= 1; j--)
			cout << j << "\t";
		cout << endl;
	}

	cout << "Pattern D" << endl;
	//Pattern D
	for (int i = 1; i <= 6; i++)
	{
		for (int j = 1; j <= 6 - i + 1; j++)
			cout << j << "\t";
		cout << endl;
	}

	return 0;
}

5.21(输出一个数字金字塔图案)编写一个嵌入的for循环,输出下面的图案:

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

int main()
{
	for (int i = 1; i <= 8; i++)
	{
		for (int j = 7 - i + 1; j >= 0; j--)
			cout << "\t";
		for (int k = 1; k <= i; k++)
			cout << pow(2, k - 1) << "\t";
		for (int z = i - 1; z >= 1; z--)
			cout << pow(2, z - 1) << "\t";
		cout << endl;
	}

	return 0;
}

5.22(输出2~1000之间的素数)修改程序清单5-17,输出2~1000(包含2和1000)之间的所有素数。每行显示8个。数字由空格分开。

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

int main()
{
	const int BEGIN_NUMBER = 2;//开始遍历的数字
	const int END_NUMBER = 1000;//结束遍历的数字
	const int NUMBER_OF_PRIMES_PER_LINE = 8;//每行输出几个素数

	bool isPrimesFlag = true;//该数是否是素数的标记字符
	int countOfPrimes = 0;//当前素数个数

	//第一层循环,从BEGIN_NUMBER到END_NUMBER对每个数进行遍历
	for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
	{
		//对第i个数判断是否为素数,只需在它的1/2大小的数中找约数
		for (int j = 2; j <= i/2; j++)
		{
			if (i % j == 0)//如果存在除了1和本身的其他约数
			{
				isPrimesFlag = false;//素数标记符设为false
				break;//跳出循环
			}
		}
		//如果是素数,打印该数,素数的个数加一
		if (isPrimesFlag)
		{
			cout << setw(5) << left << i << " ";
			countOfPrimes++;
		}
		//如果素数的个数等于每行输出素数个数的要求
		if (countOfPrimes == NUMBER_OF_PRIMES_PER_LINE)
		{
			cout << endl;//换行
			countOfPrimes = 0;//素数计数置零
		}
		isPrimesFlag = true;//将标记位设置为ture
	}


	return 0;
}

5.23(金融应用:比较不同利率下的还款金额)编写一个程序,由用户输入贷款额和贷款年限,输出不同利率下的月还款额和总还款额,利率从5%~8%,增长间隔为1/8.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
	const double INTERST_RATE = 0.05;//最初的利率
	const double FINAL_RATE = 0.08;//最终的利率
	const double INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES = 1 / 800.0;//利率增长间隔

	double loanAmount;//贷款额
	int numberOfYears;//贷款年限
	double currentYearRate = INTERST_RATE;//当前循环中的年利率
	double currentMonthRate;//当前年利率下的月利率
	double currentMonthlyPayment;//当前利率下的月还款额
	double currentTotalPayment;//当前利率下的总还款额

	//提示用户输入贷款额
	cout << "Loan Amount:";
	cin >> loanAmount;
	//提示用户输入贷款年限
	cout << "Number of Years:";
	cin >> numberOfYears;
	//输出表头
	cout << "\nInterest Rate" << "\t" << "Monthly Payment" << "\t" << "Total Payment" << endl;
	//循环进行每年的计算
	for (int i = 0; i <= (FINAL_RATE - INTERST_RATE) / INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES; i++)
	{
		currentMonthRate = currentYearRate / 12.0;//当次循环中的月利率=当次循环的年利率/12.0
		//月还款额
		currentMonthlyPayment = loanAmount * currentMonthRate / (1.0 - 1.0 / pow((1.0 + currentMonthRate), numberOfYears * 12));
		//总还款额
		currentTotalPayment = currentMonthlyPayment * numberOfYears * 12;
		cout << fixed << setprecision(3) << currentYearRate * 100.0 << "%\t\t"
			<< setprecision(2) << currentMonthlyPayment << "\t\t"
			<< setprecision(2) << currentTotalPayment << endl;
		currentYearRate += INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES;
	}
	return 0;
}

5.24(金融应用:贷款分期偿还计划)一笔贷款的月还款包括偿还本金和偿还利息。月利息可以通过月利率乘以余额(剩余本金)来计算,于是月偿还本金就等于月还款减去月偿还利息。编写一个程序,由用户输入贷款额、贷款年限和利率,输出分期还款的计划。

提示:最后一次还款后的余额可能不是0.如果是这种情况,那么应在最后一次还款额应该是正常的月还款额加上最终的余额。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
	double loanAmount;//贷款总额
	double numberOfYear;//贷款年限
	double annualInterestRate;//年利率

	cout << "Loan Amount:";
	cin >> loanAmount;
	cout << "Number of Years:";
	cin >> numberOfYear;
	cout << "Annual Interest Rate:";
	cin >> annualInterestRate;

	double interest;//利息
	double principal;//本金
	double balance = loanAmount;//余额

	//月还款额
	double monthlyPayment = (loanAmount * annualInterestRate / 1200.0) / (1 - 1 / pow(1 + annualInterestRate / 1200.0, numberOfYear * 12));
	//还款总额
	double totalPayment = monthlyPayment * numberOfYear * 12;
	cout << "\nMonthly Payment:" << fixed << setprecision(2) << monthlyPayment;
	cout << "\nTotal Payment:" << fixed << setprecision(2) << totalPayment << endl;
	//输出表头
	cout << "Payment#" << "\t" << "Interest" << "\t" << "Principal" << "\t" << "Balance" << endl;
	for (int i = 1; i <= numberOfYear * 12; i++)
	{
		//利息=月利率*余额
		interest = annualInterestRate / 1200.0 * balance;
		//还款本金=月还款-利息
		principal = monthlyPayment - interest;
		//余额=当前余额-还款本金
		balance = balance - principal;
		cout << i << "\t\t" << fixed << setprecision(2) << interest << "\t\t" << principal << "\t\t" << balance << endl;
	}

	return 0;
}

5.25(演示消去误差)当一个很大的数与一个很小的数进行运算时,可能会发生消去误差,大数可能抵消掉小数。例如,1000000000.0+0.000000001的结果是100000000.0.为了避免消去误差,获得更精确的结果,应小心选择计算对的阶。例如,当计算如下级数时,由右至左计算就会比由左至右计算获得更精确的结果:

1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n}

编写一个程序,计算上面级数的和,由左至右计算一次,再由右至左计算一次,n=50000.

#include <iostream>
using namespace std;

int main()
{
	const int N = 50000;//级数层数
	double sumOfLeftToRight = 0.0;//从左向右求和
	double sumOfRightToLeft = 0.0;//从右向左求和

	for (int i = 1; i <= N; i++)
		sumOfLeftToRight += 1.0 / (double)i;
	cout << "从左向右求和为:" << sumOfLeftToRight << endl;

	for (int i = N; i > 0; i--)
		sumOfRightToLeft += 1.0 / (double)i;
	cout << "从右向左求和为:" << sumOfRightToLeft << endl;

	return 0;
}

5.26(计算一个级数的和)编写程序,计算下面级数的和:

\frac{1}{3}+\frac{3}{5}+\frac{5}{7}+\frac{7}{9}+\frac{9}{11}+\frac{11}{13}+...+\frac{95}{97}+\frac{97}{99}

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

int main()
{
	double sum = 0.0;

	for (int i = 1; i < 99; i += 2)
		sum = (double)i / (double)(i + 2);
	cout << "级数为:" << sum << endl;

	return 0;
}

5.27(计算π)可以使用下面的级数来逼近π:

\pi =4\left ( 1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+\frac{1}{9}-\frac{1}{11}+...+\frac{(-1)^{i+1}}{2i-1} \right )

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

int main()
{
	const int N = 500000;//设置级数层数
	double pi = 0.0;//π初始值

	//循环计算级数
	for (int i = 1; i < N; i++)
		pi += pow(-1, i + 1) / ((2 * (double)i) - 1.0);
	pi *= 4;
	cout << "级数为" << N << "时,逼近的π值为:" << pi << endl;

	return 0;
}

5.28(计算e)可以使用下面的级数来逼近e:

e=1+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+...+\frac{1}{i!}

#include <iostream>
using namespace std;

int main()
{
	const int N = 20;//级数层数
	double e = 0.0;//e
	int factorial = 1;//阶乘

	for (int i = 0; i < N; i++)
	{
		//计算阶乘
		for (int j = 1; j <= i; j++)
			factorial *= j;
		//用级数计算e
		e += 1 / (double)factorial;
		factorial = 1;//将阶乘重新置为1
	}
	cout << N << "层级数逼近e为:" << e << endl;

	return 0;
}

5.29(显示闰年)编写一个程序,输出21世界(2001-2100年)中所有的闰年,每行输出10项,闰年之间间隔为一个空格。

#include <iostream>
using namespace std;

int main()
{
	const int NUMBER_PER_LINE = 10;//每行显示个数
	const int BEGIN_YEAR = 2001;//开始年份
	const int END_YEAR = 2100;//结束年份

	int numberOfLeapYear = 0;//计数闰年

	for (int i = BEGIN_YEAR; i <= END_YEAR; i++)
	{
		//判断是否为闰年
		if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
		{
			cout << i << " ";
			numberOfLeapYear++;
			//判断是否换行
			if (numberOfLeapYear % 10 == 0)
				cout << endl;
		}
	}

	return 0;
}

5.30(显示每个月的第一天)编写程序,提示用户输入一个年份及这年的第一天是星期几,输出每个月的第一天是星期几。例如,如果用户输入2013和2,表示2013年1月1日是星期二,程序应输出如下内容:

January 1,2013 is Tuesday

……

December 1,2013 is Sunday

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

int main()
{
	const int NUMBER_OF_DAYS_A_WEEK = 7;//一星期中有几天

	int year;//年份,用户输入
	int weekday;//当前年份的一月一日是星期几,用户输入
	cout << "请输入年份和当年的一月一日是星期几:";
	cin >> year >> weekday;
	cout << endl;

	int month_num;//月份数字表示
	//月份,字符串表示
	string month_str[12] = { "January","February","March","April",
		"May","June","July","August","September",
		"October","November","December" };
	//星期,字符串表示
	string week_str[7] = { "Sunday","Monday","Tuesday","Wednesday",
		"Thursday","Friday","Saturday" };
	int dayNumber = 0;//从year的第一天到当前月份第一天的总天数
	//循环遍历每个月
	for (month_num = 0; month_num < 12; month_num++)
	{
		dayNumber = 0;
		switch (month_num)
		{
		case 12:
			dayNumber += 31;
		case 11:
			dayNumber += 30;
		case 10:
			dayNumber += 31;
		case 9:
			dayNumber += 30;
		case 8:
			dayNumber += 31;
		case 7:
			dayNumber += 31;
		case 6:
			dayNumber += 30;
		case 5:
			dayNumber += 31;
		case 4:
			dayNumber += 30;
		case 3:
			dayNumber += 31;
		case 2:
			//判断是否为闰年
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
				dayNumber += 29;
			else
				dayNumber += 28;
		case 1:
			dayNumber += 31; break;
		defaule:break;
		}
		cout << month_str[month_num] << " 1," << year << " is " << week_str[(dayNumber + weekday) % 7] << endl;
	}

	return 0;
}

5.31(输出日历)编写程序,提示用户输入年份和这一年的第一天是星期几,输出这一年的日历。例如,如果用户输入2013和2,表示2013年1月1日是星期二,则程序应输出此年中每个月的日历。

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

int main()
{
	const int NUMBER_OF_DAYS_A_WEEK = 7;//一星期中有几天

	int year;//年份,用户输入
	int weekday;//当前年份的一月一日是星期几,用户输入
	cout << "请输入年份和当年的一月一日是星期几:";
	cin >> year >> weekday;
	cout << endl;

	int fristDayOfMonth;//每个月的第一天是星期几
	int month_num;//月份数字表示
	//月份,字符串表示
	string month_str[12] = { "January","February","March","April",
		"May","June","July","August","September",
		"October","November","December" };
	//每个月有多少天
	int DayNumberOfMonth[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
	//判断是否为闰年,闰年的时,二月份为29天
	if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
		DayNumberOfMonth[1] = 29;
	else
		DayNumberOfMonth[1] = 28;

	int dayNumber = 0;//从year的第一天到当前月份第一天的总天数
	//循环遍历每个月,得出当前月份的第一天到当年1月1号的总天数
	for (month_num = 0; month_num < 12; month_num++)
	{
		dayNumber = 0;
		switch (month_num)
		{
		case 12:
			dayNumber += 31;
		case 11:
			dayNumber += 30;
		case 10:
			dayNumber += 31;
		case 9:
			dayNumber += 30;
		case 8:
			dayNumber += 31;
		case 7:
			dayNumber += 31;
		case 6:
			dayNumber += 30;
		case 5:
			dayNumber += 31;
		case 4:
			dayNumber += 30;
		case 3:
			dayNumber += 31;
		case 2:
			//判断是否为闰年
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
				dayNumber += 29;
			else
				dayNumber += 28;
		case 1:
			dayNumber += 31; break;
		defaule:break;
		}

		cout << "\t\t" << month_str[month_num] << "  " << year << endl;//输出表头
		cout << "----------------------------------------------------------" << endl;//输出表头
		cout << "Sun" << "\t" << "Mon" << "\t" << "Tue" << "\t" << "Wed" << "\t" << "Thu" << "\t" << "Fri" << "\t" << "Sat" << endl;//输出表头

		int i;//循环变量
		int flagOfLine = 0;//换行标志位
		fristDayOfMonth = (dayNumber + weekday) % 7;//计算当前月份的第一天是星期几

		//第一列是星期日,根据当前的星期几,计算第一行需要输出几次空格
		for (i = 0; i < fristDayOfMonth % NUMBER_OF_DAYS_A_WEEK; i++)
		{
			cout << " " << "\t";
			flagOfLine++;//换行符加1
		}

		//打印输出表的主要内容
		for (int j = 1; j <= DayNumberOfMonth[month_num]; j++)
		{
			cout << j << "\t";
			flagOfLine++;
			//判断是否需要换行
			if (flagOfLine == NUMBER_OF_DAYS_A_WEEK)
			{
				cout << "\n" << endl;
				flagOfLine = 0;//清零,重新计数
			}
		}
		cout << "\n\n";
	}
	return 0;
}

5.32(金融应用:计算零取整存)假定你每月向一个储蓄账户存入100美元,利率是5%。那么,月利率是0.05/12=0.00417.第一个月后,账面金额变为:100*(1+0.00417)=100.417

第二个月后,账面金额变为:(100+100.417)*(1+0.00417)=201.252

第三个月后,账面金额变为:(100+201.252)*(1+0.00417)=302.507

以此类推,编写一个程序,提示用户输入每月存入金额(如100)、年利率(如5)、月数(如6),输出指定月数后账面金额。

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

int main()
{
	double monthlyDepositAmount = 0.0;//月存入金额
	double annualInterestRate = 0.0;//年利率
	double monthlyInterestRate = 0.0;//月利率
	int numberOfMonth = 0;//月数
	double totalSum = 0.0;//总额

	cout << "输入月存入金额:" << endl;
	cin >> monthlyDepositAmount;
	cout << "输入年利率:" << endl;
	cin >> annualInterestRate;
	cout << "输入月数:" << endl;
	cin >> numberOfMonth;

	monthlyInterestRate = annualInterestRate / 1200.0;

	for (int i = 0; i < numberOfMonth; i++)
	{
		totalSum = (monthlyDepositAmount + totalSum) * (1.0 + monthlyInterestRate);
	}
	cout << numberOfMonth << "月后,账面金额为:" << totalSum << endl;

	return 0;
}

5.33(金融应用:计算CD价值)假定你向CD投入10 000美元,年度百分比收益率为5.75%。一个月后,CD价值为

10 000+10 000*5.75/1200=10047.91

第二个月后,CD价值为:10047.91+10047.91*5.75/1200=10096.06

第三个月后,CD价值为:10096.06+10096.06*5.75/1200=10144.43

以此类推。编写程序,提示用户输入金额(如10000)、年度百分比收益率(如5.75)和月数(如18),输出表格。

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

int main()
{
	double initialAmount = 0.0;//初始存入金额
	double annualRate = 0.0;//年利率
	unsigned int numberOfMonth = 0;//月数
	double totalSum = 0.0;//CD价值,总金额

	cout << "Enter the initial deposit amount:";
	cin >> initialAmount;
	cout << "Enter annual percentage yield:";
	cin >> annualRate;
	cout << "Enter maturity period (number of months):";
	cin >> numberOfMonth;

	cout << "Month" << "\t" << "CD Value" << endl;
	totalSum = initialAmount;
	for (int i = 1; i <= numberOfMonth; i++)
	{
		totalSum = totalSum + totalSum * annualRate / 1200.0;
		cout << i << "\t" << fixed << setprecision(2) << totalSum << endl;
	}

	return 0;
}

5.34(游戏:彩票)重写程序清单3-7,Lottery.cpp,生成一个两位数的彩票。一个数中的两个数字不同。(提示:生成第一个数字。使用循环重复生成第二个数字,直到它同第一个数字不同)

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
	//生成两个不相同的随机数
	srand(time(0));
	int lotteryDigit1 = rand() % 10;//随机数1
	int lotteryDigit2 = rand() % 10;//随机数2
	//如果两个随机数相同,进入循环
	while (lotteryDigit1 == lotteryDigit2)
		lotteryDigit2 = rand() % 10;//重新生成随机数2

	cout << "Enter your lottery pick (two digits):";
	int guess;
	cin >> guess;

	int guessDigit1 = guess / 10;
	int guessDigit2 = guess % 10;

	cout << "The lottery number is " << lotteryDigit1 << lotteryDigit2 << endl;

	if (guessDigit1 == lotteryDigit1 && guessDigit2 == lotteryDigit2)
		cout << "Exact match: you win $10,000" << endl;
	else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2)
		cout << "Macth all digits: you win $3,000" << endl;
	else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2)
		cout << "Match one digit:you win $1,000" << endl;
	else
		cout << "Sorry,no match" << endl;

	return 0;
}

5.35(完全数)如果一个正整数等于它的所有正因子(不包括它本身)之和,则这个正整数称为完全数,例如,6为第一个完全数,因为6=3+2+1.下一个为28=14+7+4+2+1.小于10 000的完全数有四个。编写程序找出这4个数字。

#include <iostream>
using namespace std;

int main()
{
	const int BEGIN_NUMBER = 1;//开始遍历数字
	const int END_NUMBER = 10000;//结束遍历数字

	int sum = 0;//正因子之和

	for (int i = BEGIN_NUMBER; i < END_NUMBER; i++)
	{
		for (int j = 1; j <= i / 2; j++)
		{
			if (i % j == 0)//如果是因子
				sum += j;//
		}
		if (sum == i)//判断因子总和和该数是否相等
			cout << i << endl;
		sum = 0;
	}

	return 0;
}

5.36(游戏:剪刀,石头,布)程序设计练习3.15给出了玩剪刀石头布游戏的程序,重写程序,使其一直进行直到用户或计算机赢两次以上。

#include<iostream>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	int numberOfUserWin = 0;//用户赢的次数
	int numberOfComputerWin = 0;//电脑赢的次数

	srand(time(0));
	while (numberOfComputerWin < 2 && numberOfUserWin < 2)
	{
		int computerInput = rand() % 3;//电脑随机得到一个0,1,2的数

		//提示用户输入
		cout << "scissor(0),rock(1),paper(2):";
		int userInput;
		cin >> userInput;

		//输出电脑是剪刀石头还是布
		cout << "The computer is ";
		switch (computerInput)
		{
		case 0:cout << "scissor"; break;
		case 1:cout << "rock"; break;
		case 2:cout << "paper"; break;
		};
		//输出用户的剪刀石头还是布
		cout << ". You are ";
		switch (userInput)
		{
		case 0:cout << "scissor"; break;
		case 1:cout << "rock"; break;
		case 2:cout << "paper"; break;
		default:cout << "inputting is error"; return 0;
		};

		if (computerInput == userInput)//相等则平局
			cout << " too. It is a draw" << endl;
		else if (userInput == 0 && computerInput == 2 || userInput == 1 && computerInput == 0
			|| userInput == 2 && computerInput == 1)
		{
			cout << ". You won" << endl;
			numberOfUserWin++;
		}
		else
		{
			cout << ". You loss" << endl;
			numberOfComputerWin++;
		}
	}

	return 0;
}

5.37(求和)编写程序计算下列数的总和。

\frac{1}{1+\sqrt{2}}+\frac{1}{\sqrt{2}+\sqrt{3}}+\frac{1}{\sqrt{3}+\sqrt{4}}+...+\frac{1}{\sqrt{624}+\sqrt{625}}

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

int main()
{
	const int BEGIN_NUMBER = 1;
	const int END_NUMBER = 625;

	double total = 0.0;

	for (int i = BEGIN_NUMBER; i < END_NUMBER - 1; i++)
		total += 1.0 / (sqrt(i) + sqrt(i + 1));

	cout << "数列的总和为:" << total << endl;

	return 0;
}

5.38(商业应用:检测ISBN)使用循环来简化程序设计练习3.35.

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

int main()
{
	cout << "Enter the first 9 digits of an ISBN as integer:";
	int isbn_10;//用户输入ISBN的前九位数字
	cin >> isbn_10;

	int digit;//中间变量,用来临时存放第n位ISBN值
	int sum = 0;//九个数字计算出来的总和
	cout << "The ISBN-10 number is ";
	//输出前九位数字
	for (int i = 9; i > 0; i--)
	{
		digit = (isbn_10 % (int)pow(10, i)) / ((int)pow(10, i - 1));
		cout << digit;//输出该位数字
		sum += digit * (10 - i);//累加和
	}
	if (sum % 11 == 10)//如果校验和为10,输出为X
		cout << "X" << endl;
	else
		cout << sum % 11 << endl;
	return 0;
}

5.39(金融应用:计算出销售额)你刚刚在百货公司开始做销售工作。你的工资包括基础工资与提成。基础工资为$5000.下面的计划表来决定提成率。注意,这是一个累进税率。第一个$5000为8%,第二个$5000为10%,剩下的为12%。如果你销售额为25 000,则提成为5000*8%+5000*10%+15 000*12%=2700。你的目标是每年赚$30 000.编写程序,使用do-while循环,计算出赚取$30 000需要最少的销售额。

#include <iostream>
using namespace std;

const float BASIC_WAGE = 5000.0;//基础工资
const float	TARGET_WAGE = 30000.0;//目标工资

const float FIRST_STAGE = 0.0;			//第一阶段
const float FIRST_STAGE_RATE = 8.0;		//第一阶段税率
const float SECOND_STAGE = 5000.0;		//第二阶段
const float SECOND_STAGE_RATE = 10.0;	//第二阶段税率
const float THIRD_STAGE = 10000.0;		//第三阶段
const float THIRD_STAGE_RATE = 12.0;	//第三阶段税率

int main()
{
	float sale = 0.0;//销售额
	float wage = BASIC_WAGE;//总工资
	do
	{
		wage = BASIC_WAGE;//总工资
		if (sale > FIRST_STAGE && sale <= SECOND_STAGE)
			wage += sale * FIRST_STAGE_RATE / 100.0;//第一阶段
		else if (sale > SECOND_STAGE && sale <= THIRD_STAGE)
			wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一阶段
			(sale - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0;//第二阶段
		else if (sale > THIRD_STAGE)
			wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一阶段
			(THIRD_STAGE - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0 +//第二阶段
			(sale - THIRD_STAGE) * THIRD_STAGE_RATE / 100.0;//第三阶段
		sale += 0.01;//每次增加一分钱
	} while (wage <= TARGET_WAGE);//当总工资大于每年工资目标结束循环

	cout << "赚取$" << TARGET_WAGE << "需要最少$" << sale << "销售额" << endl;

	return 0;
}

5.40(模拟实验:正面或背面)编写程序,模拟抛硬币1百万次,输出正面与背面出现的次数。

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	const int NUMBER = 1000000;//设置次数为一百万次

	srand(time(0));
	int front = 0;//正面出现次数
	int reverse = 0;//反面出现次数
	int i = NUMBER;//循环次数
	while (i--)
		if (rand() % 2)//奇数即对2取余为1的数为正面
			front++;
		else//偶数为反面
			reverse++;

	cout << "正面出现次数:" << front << ",反面出现次数:" << reverse << endl;
	return 0;
}

5.41(最大数出现的次数)编写程序,读取整数,找出其中的最大值,并计算它出现的次数。规定输入以数字0为结尾。假定你输入3 5 2 5 5 5 0;那么程序找出最大值为5,它出现的次数为4.(提示:创建两个变量max和count。max存储当前最大的数字,count存储它出现的次数。初始化时,将第一个数字赋给max,1赋给count。与max比较子序列中的每个数字。如果数字大于max,将他赋给max,将count重置为1.如果数字等于max,则将count加1)

#include <iostream>
using namespace std;

int main()
{
	int max, count = 0;
	cout << "Enter number:";
	cin >> max;
	//如果只输入一个0,结束程序
	if (max == 0)
		return 0;
	else//输入第一个数不为0,count加1
		++count;

	while (1)
	{
		int number;
		cin >> number;
		if (number == 0)//0为结尾数字,遇到0结束循环
			break;
		else if (number < max)//小于最大值,跳出本次循环
			continue;
		else if (number == max)//等于最大值,最大值出现次数加一
			++count;
		else//大于最大值,最大值重新赋值,最大值数量变为1
			max = number, count = 1;
	}
	cout << "The largest number is " << max << endl
		<< "The occurrence count of the largest number is " << count << endl;
	return 0;
}

5.42(金融应用:计算销售额)重新编写程序设计练习5.39,要去如下:

使用for循环代替do-while循环。

让用户输入COMMISSON_SOUGHT,而不是将它设定为常量。

#include <iostream>
using namespace std;

const float BASIC_WAGE = 5000.0;//基础工资
//const float TARGET_WAGE = 30000.0;//目标工资

const float FIRST_STAGE = 0.0;			//第一阶段
const float FIRST_STAGE_RATE = 8.0;		//第一阶段税率
const float SECOND_STAGE = 5000.0;		//第二阶段
const float SECOND_STAGE_RATE = 10.0;	//第二阶段税率
const float THIRD_STAGE = 10000.0;		//第三阶段
const float THIRD_STAGE_RATE = 12.0;	//第三阶段税率

int main()
{
	float COMMISSION_SOUGHT;//期待工资
	cout << "请输入COMMISSION_SOUGHT期待总工资:";
	cin >> COMMISSION_SOUGHT;

	float sale = 0.0;//销售额

	//当总工资大于每年工资目标结束循环
	for (float wage = BASIC_WAGE; wage <= COMMISSION_SOUGHT; sale += 0.01)//每次增加一分钱
	{
		wage = BASIC_WAGE;//总工资
		if (sale > FIRST_STAGE && sale <= SECOND_STAGE)
			wage += sale * FIRST_STAGE_RATE / 100.0;//第一阶段
		else if (sale > SECOND_STAGE && sale <= THIRD_STAGE)
			wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一阶段
			(sale - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0;//第二阶段
		else if (sale > THIRD_STAGE)
			wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一阶段
			(THIRD_STAGE - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0 +//第二阶段
			(sale - THIRD_STAGE) * THIRD_STAGE_RATE / 100.0;//第三阶段

	}

	cout << "赚取$" << COMMISSION_SOUGHT << "需要最少$" << sale << "销售额" << endl;

	return 0;
}

5.43(模拟实验:倒计时)编写程序,提示用户输入秒数,每一秒均显示信息,当时间用完时程序结束。

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

int main()
{
	//获取用户输入秒数
	cout << "Enter the number of seconds:";
	int seconds;
	cin >> seconds;
	//获取当前总秒数
	int totalTime = time(0);

	while (seconds > 0)
	{
		while ((time(0) - totalTime) == 0);//循环等待,经过一秒后跳出循环
		totalTime = time(0);//将totalTIme付志伟·重新赋值为当前总秒数
		cout << seconds;
		//判断second单词的单复数形式
		if (seconds == 1)
			cout << " second";
		else
			cout << " seconds";
		cout << " remaining" << endl;
		seconds--;
	}
	cout << "Stopped";
	return 0;
}

5.44(蒙特卡洛模拟实验)一个正方形分为4个小的区域,如果向正方形投掷飞镖1 000 000次,那么飞镖进入奇数区域的可能性是多少?编写程序模拟过程并输出结果。

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	int area1 = 0, area2 = 0, area3 = 0, area4 = 0;
	int times = 1000000;//投掷飞镖的次数
	srand(time(0));
	float den = RAND_MAX / 2.0;//将分母设置为随机数最大值的一半

	while (times--)
	{
		int number = rand();//产生x坐标的随机数
		float point_X = float(number - den) / den;
		number = rand();//产生y坐标的随机数
		float point_Y = float(number - den) / den;
		//如果x的坐标值小于0,则该点在区域1
		if (point_X < 0)
			area1++;
		//x坐标不小于0,y坐标小于0,则点在区域4
		else if (point_Y < 0)
			area4++;
		//横纵坐标之和小于1,该点在区域3
		else if (point_X + point_Y < 1)
			area3++;
		//横纵坐标大于0,且之和大于1,该点在区域2
		else
			area4++;
	}
	cout << "飞镖飞入奇数区域的可能性为:" << float(area1+area3)/float(area1+area2+area3+area4) << endl;
	return 0;
}

5.45(数学:组合)编写程序,输出整数1~7内两个数字的所有可能的组合。同时,输出所有组合的总的个数。

#include <iostream>
using namespace std;

int main()
{
	const int BEGIN_DIGIT = 1;//开头的数字
	const int END_DIGIT = 7;//结尾的数字

	unsigned int number = 0;//数字组合的计数变量

	for (int i = BEGIN_DIGIT; i <= END_DIGIT; i++)
	{
		for (int j = i + 1; j <= END_DIGIT; j++)
		{
			cout << i << "\t" << j << "" << endl;
			number++;
		}
	}
	cout << "The total number of all combinations is " << number;

	return 0;
}

5.46(计算机系统结构:位操作)一个short值占16位。编写程序,提示用户输入一个short类型的整数,输出这个整数的16位表示。

#include <iostream>
using namespace std;

int main()
{
	//获取用户输入的short型整数
	cout << "Enter an integer:";
	short integer;
	cin >> integer;

	for (int bits = 0; bits < sizeof(short) * 8; bits++)
	{
		//获取每一比特位
		short bit;
		bit = integer << bits;
		bit = bit >> (sizeof(short) * 8 - 1);
		cout <<"The bits are "<<abs(bit);
	}

	return 0;
}

5.47(统计学:计算均值和标准差)在商业应用中,经常会需要计算数据的均值与标准差。均值为数字的平均值。标准差为一个统计数值,告诉你一组数据中所有数据是多紧密地聚集在均值周围。例如,一个班中学生的平均年龄为多少?年龄有多相近?如果所有同学都为相同的年龄,则标准差为0.编写程序,提示用户输入10个数字,使用下列公式输出这些数字的均值和标准差:

mean=\frac{\sum_{i=1}^{n}x_{i}}{n}=\frac{x_1+x_2+x_3+...+x_n}{n}    deviation=\sqrt{\frac{\sum_{i=1}^{n}x_{i}^{2}-\frac{\left ( \sum_{i=1}^{n}x_i \right )^2}{n}}{n-1}}

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

int main()
{
	//获取用户输入的十个整数
	cout << "Enter ten numbers:";
	float n = 10.0;//整数个数
	float number[10] = { 0.0 };
	for (int i = 0; i < 10; i++)
		cin >> number[i];
	//总数
	float total = 0;
	//计算平均值
	float mean = 0.0;
	for (int i = 0; i < 10; i++)
		total += number[i];
	mean = total / n;
	//计算标准差
	float deviation = 0.0;
	total = 0.0;
	for (int i = 0; i < 10; i++)
		total += (number[i] - mean) * (number[i] - mean);

	deviation = sqrt(total / (n-1));

	cout << "The mean is " << mean << endl;
	cout << "The standard deviation is " << deviation << endl;

	return 0;
}

5.48(计算大写字母)编写一个程序,提示用户输入一个字符串,输出字符串中大写字母的个数。

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

int main()
{
	cout << "Enter a string : ";
	string str;
	getline(cin, str);//读取一行
	
	int count = 0;//大写字母数量
	for (int i = 0; i < str.length(); i++)
		if (str[i] >= 'A' && str[i] <= 'Z')
			count++;

	cout << "The number of uppercase letter is " << count;

	return 0;
}

5.49(最长公共前缀)编写程序,提示用户输入两个字符串,输出字符串的最长公共前缀。

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

int main()
{
	//获取用户输入的s1字符串
	cout << "Enter s1:";
	string s1;
	getline(cin, s1);
	//获取用户输入的s2字符串
	cout << "Enter s2:";
	string s2;
	getline(cin, s2);
	//定义共同前缀变量
	string commonPrefix;
	//遍历寻找共同前缀
	for (int i = 0; i < min(s1.length(), s2.length()); i++)
	{
		if (s1[i] == s2[i])
			commonPrefix.push_back(s1[i]);//如果相同,将该字符压入变量末尾
		else
			break;
	}
	if (commonPrefix.length() == 0)
		cout << s1 << " and " << s2 << " have no common prefix";
	else
		cout << "The common prefix is " << commonPrefix;

	return 0;
}

5.50(倒置字符串)编写程序,提示用户输入字符串,以相反顺序输出字符串。

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

int main()
{
	//获取用户输入的字符串
	cout << "Enter a string:";
	string str;
	getline(cin, str);
	//反顺序输出
	cout << "The reversed string is ";
	for (int i = str.length(); i > 0; i--)
		cout << str[i - 1];

	return 0;
}

5.51(商业:检测ISBN-13)ISBN-13为识别图书的新的标准。它使用13个数字d1d2d3d4d5d6d7d8d9d10d11d12d13。最后一个数字d13为校验和,使用下列公式由其他数字得出:

10-(d1=3d2+d3+3d4+d5+3d6+d7+3d8+d9+3d10+d11+3d12)%10

如果校验和为10,则用0来代替。程序应该将输入读取为字符串。

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

int main()
{
	//获取用户输入的前12个数字
	cout << "Enter the first 12 digits of an ISBN-13 as a string:";
	string ISBN_13;
	cin >> ISBN_13;
	//如果不足12个,打印提示信息,结束程序
	if (ISBN_13.length() < 12)
	{
		cout << ISBN_13 << " is an invalid input";
		return 0;
	}
	//将string类型转换为整数int
	int isbn[12] = { 0 };
	for (int i = 0; i < ISBN_13.length(); i++)
		isbn[i] = ISBN_13[i] - '0';
	//计算d13
	int d13 = 0;
	for (int i = 0; i < ISBN_13.length(); i++)
		if (i % 2 == 0)
			d13 += isbn[i];
		else
			d13 += 3 * isbn[i];
	d13 = 10 - (d13 % 10);
	//判断d13是否为10
	cout << ISBN_13;
	if (d13 == 10)
		cout << 0;
	else
		cout << d13;

	return 0;
}

5.52(处理字符串)编写程序,提示用户输入字符串,输出奇数下标位置的字符。

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

int main()
{
	//获取用户输入的字符串
	cout << "Enter a string:";
	string str;
	getline(cin,str);
	//输出奇数下标位置字符
	for (int i = 0; i < str.length(); i++)
		if (i % 2 == 1)
			cout << str[i];

	return 0;
}

5.53(计算元音和辅音)将字母A、E、I、O、U定为元音。编写程序,提示用户输入字符串,输出字符串中元音和辅音的个数。

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

int main()
{
	//获取用户输入的字符串
	cout << "Enter a string:";
	string str;
	getline(cin, str);

	int numberOfVowels = 0;//元音字母个数
	int numberOfConsonants = 0;//辅音字母个数
	//遍历判断每一个字符属于元音还是辅音
	for (int i = 0; i < str.length(); i++)
	{
		//元音
		if (str[i] == 'A' || str[i] == 'a'
			|| str[i] == 'E' || str[i] == 'e'
			|| str[i] == 'I' || str[i] == 'i'
			|| str[i] == 'O' || str[i] == 'o'
			|| str[i] == 'U' || str[i] == 'u')
			numberOfVowels++;
		//辅音,判断是否为字母,否则可能把空格、数字等算作字母
		else if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
			numberOfConsonants++;
	}
	cout << "The number of vowels is " << numberOfVowels << endl;
	cout << "The number of consonants is " << numberOfConsonants << endl;

	return 0;
}

5.54(计算文件中字母的个数)编写程序,计算名为countletter.txt文件中字母的个数。在本题中我随机生成了一个countletter.txt文件。详情见代码。

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	//随机生成一个字符串
	srand(time(0));
	string str;
	for (int i = 0; i < 100; i++)
		str.push_back(char(rand() % 128));//ASCII码值
	//将这个字符串存储到文件中并保存
	ofstream makeFile;
	makeFile.open("countletter.txt");
	makeFile << str << endl;
	makeFile.close();
	//打开文件,读取字符串
	ifstream readFile;
	readFile.open("countletter.txt");
	string data;
	readFile >> data;
	readFile.close();
	//遍历查看字符串中有多少个字母
	int numberOfLetter = 0;
	for (int i = 0; i < str.length(); i++)
		if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
			numberOfLetter++;

	cout << "countletter.txt文件中字母的个数为:" << numberOfLetter << endl;

	return 0;
}

5.55(数学辅导)编写程序,输出运行样例中所示的菜单。输入1/2/3/4选择加法、减法、乘法、或者除法测试。在测试结束后,菜单会重新显示。你可以选择另一个测试或者输入5退出系统。每个测试随机生成两个仅有一个数字的数。对于减法来说,number1-number2,number1大于或等于number2.对于除法来说,number1/number2,number2不为0.

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;

int main()
{
	srand(time(0));
	int number1, number2;
	while (1)
	{
		//生成菜单栏
		cout << "Main menu\n"
			<< "1: Addition\n"
			<< "2: Subtraction\n"
			<< "3: Multiplication\n"
			<< "4: Division\n"
			<< "5: Exit\n"
			<< "Enter a choice: ";
		int choice;//用户选择的序号
		cin >> choice;//用户输入序号
		int answer;//用户输入的答案
		number1 = rand() % 10;//生成一个随机数
		number2 = rand() % 10;
		switch (choice)
		{
		case 1://加法
			cout << "What is " << number1 << " + " << number2 << "? ";
			cin >> answer;
			if (answer == number1 + number2)
				cout << "Correct\n\n";
			else
				cout << "Your answer is wrong, The correct answer is " << number1 + number2 << "\n\n";
			break;
		case 2://减法,减法中第一个数字要大于第二个数字,所以取两个随机数中的较大值作为第一个数,较小值作为第二个数
			cout << "What is " << max(number1, number2) << " - " << min(number1, number2) << "? ";
			cin >> answer;
			if (answer == abs(number1 - number2))
				cout << "Correct\n\n";
			else
				cout << "Your answer is wrong, The correct answer is " << abs(number1 - number2) << "\n\n";
			break;
		case 3://乘法
			cout << "What is " << number1 << " × " << number2 << "? ";
			cin >> answer;
			if (answer == number1 * number2)
				cout << "Correct\n\n";
			else
				cout << "Your answer is wrong, The correct answer is " << number1 * number2 << "\n\n";
			break;
		case 4://除法
			//判断number2是否为0
			if (number2 == 0)//如果number2为0,则进去while循环
				while ((number2 = rand() % 10) == 0);//直到number2得到一个不为0的随机数,跳出循环
			cout << "What is " << number1 << " / " << number2 << "? ";
			cin >> answer;
			if (answer == number1 / number2)
				cout << "Correct\n\n";
			else
				cout << "Your answer is wrong, The correct answer is " << number1 + number2 << "\n\n";
			break;
		case 5://退出程序
			cout << "exit" << endl;
			return 0;
		default:
			break;
		}
	}

	return 0;
}

5.56(拐点坐标)假定一个有n条边的正多边形中心为(0,0),一个点在3点钟方向。编写程序,提示用户输入边的个数和正多边形外接圆的半径,输出正多边形拐点的坐标。

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

int main()
{
	//定义常量PI
	const float PI = 3.14159;
	//获取用户输入的多边形的边数
	cout << "Enter the number of the sides: ";
	int numbersOfSides;
	cin >> numbersOfSides;
	//获取圆的半径
	cout << "Enter the radius of the bounding circle: ";
	float radius;
	cin >> radius;
	//输出多边形各个顶点的坐标
	cout << "The coordinates of the points on the polygon are" << endl;
	for (int i = 0; i < numbersOfSides; i++)
	{
		float x = radius * cos(2 * PI / numbersOfSides * i);
		float y = radius * sin(2 * PI / numbersOfSides * i);
		cout << "(" << x << ", " << y << ")" << endl;
	}

	return 0;
}

5.57(检测密码)有些网站施加一些对密码的规定。假定密码规则如下:

  • 密码必须有至少8位字符
  • 密码必须仅包含字母和数字
  • 密码必须包含至少两个数字

编写程序,提示用户输入密码,如果遵循了密码规则,则显示vaild password,否则显示invalid password。

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

int main()
{
	string password;//密码字符串,用户输入
	cout << "Please put in a password: ";
	cin >> password;

	int numberOfDigit = 0;//密码中包含数字的数量
	int numberOfLetter = 0;//密码中包含字母的数量
	int numberOfOthers = 0;//密码中包含的其他符号
	//判断规则一:密码必须有至少8位字符
	if (password.length() >= 8)
	{
		for (int i = 0; i < password.length(); i++)
		{
			//判断是否为数字
			if (password[i] >= '0' && password[i] <= '9')
				numberOfDigit++;
			//判断是否为字母
			else if (password[i] >= 'a' && password[i] <= 'z' || password[i] >= 'A' && password[i] <= 'Z')
				numberOfLetter++;
			//其他字符
			else
			{
				numberOfOthers++;
				break;//跳出循环,因为违反规则2仅包含字母和数字
			}
		}
		//判断是否符合规则2和规则3
		if (numberOfOthers == 0 && numberOfDigit >= 2 && numberOfLetter > 0)
		{
			cout << "valid password";
			return 0;
		}
		else
		{
			cout << "invalid password";
			return 0;
		}
	}
	else
		cout << "invalid password";

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40836442/article/details/107280963