趣味算法入门

1.百钱百鸡问题

#include<iostream>
using namespace std;
int main()
{
	int x, y, z;//x:公鸡 y:母鸡 z: 小鸡
	for ( x = 0; x <= 20; x++)
	{
		for (y = 0; y <= 33; y++)
		{
			z = 100 - x - y;//这里x,y确定了,那么z的值也一定可以确定了,不用在穷举z了
			if ((5 * x + 3 * y + z / 3 == 100) && (x + y + z == 100))
			{
				cout << "公鸡:" << x ;
				cout << "母鸡:" << y;
				cout << "小鸡:" << z << endl;
			}
			
		}
	}
}

2.借书方案

#include<iostream>
using namespace std;
int main()
{
	int a, b, c,i=0;
	for (a = 1; a <= 5; a++)
	{
		for (b = 1; b <= 5 && a != b; b++)//这里可以判断一次a是否和b相等,如果相等可以直接不用进行c的循环
		{
			for (c = 1; c <= 5; c++)
			{
				if (a != c && b != c)
				{
					cout << "A: " << a << " B;" << b << " C: " << c << " | ";
					i++;
				}
				if (i % 4 == 0)
				{
					cout << endl;
				}
			}
		}
	}
	cout << "一共有" << i << "种" << endl;
}

3.打鱼还是晒网

#include<iostream>
using namespace std;
struct Date
{
	int year;
	int month;
	int day;
};
bool runyear(int year)//判断是否为闰年
{
	if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
	{
		return true;
	}
	return false;
}
int countdat(Date& d)
{
	int Month[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };//每一个平年的天数
	int totalday = 0;
	//接下来先计算年的天数,然后是月,最后是日

	//1.计算到前一年所需要的天数
	for (int year = 1990; year < d.year; year++)
	{
		if (runyear(year))//如果是闰年,加366天
		{
			totalday += 366;
		}
		else
		{
			totalday += 365;
		}
	}

	//2.计算该年的月份的天数
	if (runyear(d.year)) { Month[2]++; }//如果是闰年,那么2月份应该为29天
	for (int i = 1; i < d.month; i++)
	{
		totalday += Month[i];//将本年月份的天数加上去
	}
	//3.将本年的日加上去
	totalday += d.day;


	return totalday;
}

int main()
{
	Date d;
	int totalday, result;//totalday指的是一共的天数,result是对5取余
	cout << "请输入年月日:";
	cin >> d.year >> d.month >> d.day;
	totalday = countdat(d);
	result = totalday % 5;
	if (result > 0 && result < 4)
	{
		cout << "今天打渔" << endl;
	}
	else
	{
		cout << "今天晒网" << endl;
	}
}

抓交通肇事犯

一脸卡车撞人逃跑,三人目击,但没有记住车牌号,之记下了车号的特征。甲:牌照前两位数是相同的 乙:牌照的后两位是也是相同的,但是与前两位不同 丙:他是数学家,四位的车号刚好是一个整数的平方。

请求出车牌号

#include<iostream>
using namespace std;

int main()
{
	int i, j,k, temp;//i代表前两位,j代表后两位
	int flag = 0;//判断是否求出结果的,如果是改为1,则直接退出循环,减少循环次数。
	for (i = 1; i <= 9; i++)
	{
		if (flag) { break; }
		for (j = 1; j <= 9; j++)
		{
			if (flag) { break; }
			if (i != j)
			{
				k = 1000 * i + 100 * i + 10 * j + j;
			for (temp = 31; temp <= 99; temp++)
			{
				if (k == temp * temp)
				{
					cout << "车牌号为:" << k << endl;
					flag = 1;
					break;
				}
			}
			}
			
		}
	}
}
posted on 2023-04-10 20:31  许七安gyg  阅读(49)  评论(0编辑  收藏  举报
$(document).ready(function() { // 禁止右键 $(document).bind("contextmenu", function(){return false;}); // 禁止选择 $(document).bind("selectstart", function(){return false;}); // 禁止Ctrl+C 和Ctrl+A $(document).keydown(function(event) { if ((event.ctrlKey&&event.which==67) || (event.ctrlKey&&event.which==86)) { //alert("对不起,版权所有,禁止复制"); return false; } }); });