借书问题(三人借五本书)(C++)

题目链接:https://www.bilibili.com/video/av21356335?p=2

问题描述:小明有五本新书,要借给A、B、C三个人,若每人每次只能借一本,则可以由多少种借法?

问题分析:属于数学中的排列组合问题,即求从5个数中取3个不同数的组合的情况

使用三重for循环,只要每层循环的值不相等,最后就记录为一次

 

#include<iostream>
using namespace std;

int main(void)
{
	int a, b, c;
	int count = 0;  //count用于记录次数

	cout << "三人所选的书号分别为:" << endl;
	for (a = 1; a <= 5; a++)
		for (b = 1; b <= 5; b++)
			for (c = 1; c <= 5; c++)
				if ((a != b) && (a != c) && (b != c))
				{
					cout << a << " " << b << " " << c <<"    ";
					count++;
					
					//每行输出四种情况然后换行
					if (count % 4 == 0)
						cout << endl;
				}
	cout << "共有" << count << "种情况!" << endl;

}

               

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是C++图书管理系统中借书还书的示例代码: ```cpp #include <iostream> #include <fstream> #include <string> using namespace std; // 定义图书结构体 struct Book { string name; // 书名 string author; // 作者 string publisher; // 出版社 string ISBN; // ISBN号 bool borrowed; // 是否被借出 string borrower; // 借阅人 }; // 借书函数 void borrowBook(Book &book, string borrower) { if (book.borrowed) { cout << "该书已被借出!" << endl; } else { book.borrowed = true; book.borrower = borrower; cout << "借书成功!" << endl; } } // 还书函数 void returnBook(Book &book) { if (book.borrowed) { book.borrowed = false; book.borrower = ""; cout << "还书成功!" << endl; } else { cout << "该书未被借出!" << endl; } } int main() { // 读取图书信息 ifstream fin("books.txt"); int bookCount; fin >> bookCount; Book *books = new Book[bookCount]; for (int i = 0; i < bookCount; i++) { fin >> books[i].name >> books[i].author >> books[i].publisher >> books[i].ISBN >> books[i].borrowed >> books[i].borrower; } fin.close(); // 借书还书 string name, borrower; cout << "请输入要借阅的书名:"; cin >> name; bool found = false; for (int i = 0; i < bookCount; i++) { if (books[i].name == name) { found = true; if (books[i].borrowed) { cout << "该书已被借出,借阅人为:" << books[i].borrower << endl; cout << "请输入还书人姓名:"; cin >> borrower; if (books[i].borrower == borrower) { returnBook(books[i]); } else { cout << "还书人姓名错误! << endl; } } else { cout << "请输入借书人姓名:"; cin >> borrower; borrowBook(books[i], borrower); } break; } } if (!found) { cout << "未找到该书!" << endl; } // 保存图书信息 ofstream fout("books.txt"); fout << bookCount << endl; for (int i = 0; i < bookCount; i++) { fout << books[i].name << " " << books[i].author << " " << books[i].publisher << " " << books[i].ISBN << " " << books[i].borrowed << " " << books[i].borrower << endl; } fout.close(); delete[] books; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值