C++ Primer Plus 编程练习题 第五章 循环和关系表达式

发布于:2025-04-01 ⋅ 阅读:(14) ⋅ 点赞:(0)

1.整数和

#include <iostream>
using namespace std;

int main()
{
	int a,b;
	cout << "请输入第一个整数:";
	cin >> a;
	cout << "请输入第二个整数:";
	cin >> b;
	int sum = 0;
	for (int i = a; i <= b; i++)
		sum += i;
	cout << a << "和" << b << "之间的整数和为:" << sum;
	return 0;
}

2.100的阶乘

回顾array数组的用法,array<类型名, 元素个数> 数组名,定长数组

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

int main()
{
	const int arsize = 16;
	array<long double,arsize> factorials;
	factorials[0] = factorials[1] = 1;
	for (int i = 2; i < arsize; i++)
		factorials[i] = i * factorials[i - 1];
	for (int i = 0; i < arsize; i++)
		cout << i << "!=" << factorials[i]<<"\n";
	cout << factorials[100];
	return 0;
}

3.累加和

#include <iostream>
using namespace std;

int main()
{
	int sum = 0;
	int i;
	cout << "请输入i的值,输入0进行终止";
	cin >> i;
	while (i != 0)
	{
		sum += i;
		cout << "目前为止,累加和为" << sum<<"\n";
		cin >> i;
	};
	return 0;
}

4.Celo和Daphne的投资

#include <iostream>
using namespace std;

int main()
{
	int Daphne_profit = 110;
	double Cleo_profit = 105;
	int year = 1;
	while (Cleo_profit < Daphne_profit)
	{
		year += 1;
		Daphne_profit += 10;
		Cleo_profit += Cleo_profit * 0.05;
	};
	cout << "第" << year << "年时" << " C_p=" << Cleo_profit << "超过了 D_p=" << Daphne_profit << "\n";
	
	return 0;
}

5.图书销量

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

int main()
{
	string months[12] = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
	int amount[12];
	int sum = 0;
	for (int i = 0; i < 12; i++)
	{
		cout << "请输入" << months[i] << "的销售额为:"<<"\n";
		cin >> amount[i];
		sum += amount[i];
	};
	cout << "今年销售量总额为" << sum;
	return 0;
}

6.图书三年总销售量

二维数组

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

int main()
{
	const string years[3] = {"第一年","第二年","第三年"};
	const string months[12] = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
	int amount[3][12];
	int sum = 0;
	int sum_year[3] = { 0,0,0 };
	for (int i = 0; i < 3; i++)
	{
		cout << years[i] << "\n";
		for (int j = 0; j < 12; j++)
		{
			cout << "请输入" << months[j] << "的销售额为:" << "\n";
			cin >> amount[i][j];
			sum_year[i] += amount[i][j];
			sum += amount[i][j];
		};
	};
	for (int i = 0; i < 3; i++)
		cout << "第" << i+1 << "年销售额为" << sum_year[i] << "\n";
	cout << "三年销售总额为" << sum << "\n";
	return 0;
}

7.汽车信息

动态数组

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

struct Car 
{
	string productor;
	int year;
};
int main()
{
	int number;
	cout << "请输入车的数量:";
	cin >> number;
	Car * car = new Car[number];
	for (int i = 0; i < number; i++)
	{
		cout << "请输入汽车生产商:";
		cin >> car[i].productor;
		cout << "请输入汽车生产年份:";
		cin >> car[i].year;
	};
	cout << "汽车信息如下:\n";
	for (int i = 0; i < number; i++)
		cout << car[i].year << "\t"<<car[i].productor<<"\n";
	return 0;
}

8.计算单词

9.嵌套循环星号


网站公告

今日签到

点亮在社区的每一天
去签到