古代 经典问题之鸡兔同笼

这是一个鸡兔同笼的问题,只需输入鸡的数目和头的数目即可求出鸡和兔分别为多少,并却在输入不合理时会自动报错。
 
/**********************
**鸡兔同笼问题C++程序**
**********************/

#include<iostream>
using namespace std;
int main()
{
	int a,b,tou,jiao;
	cout<<"请输入头的数目"<<endl;
	cin>>tou;
	cout<<"请输入脚的数目"<<endl;
	cin>>jiao;
	if(jiao>=2*tou&&jiao%2==0)
	{
		b=jiao/2-tou;
	a=tou-b;
	cout<<"鸡的数目为:"<<a
		<<"兔的数目为:"<<b
		<<endl;
	}
	else
		cout<<"输入错误"<<endl;


	return 0;
}


这个程序不完美的地方在于只能计算一次,稍作改进可以无数次计算,按指定键退出。

改进后程序如下:

// jitutonglong.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
	
	int a,b,tou,jiao,key=1;
	char exit;
	while(key)
	{
		cout<<"请输入头的数目"<<endl;
	cin>>tou;
	cout<<"请输入脚的数目"<<endl;
	cin>>jiao;
	if(jiao>=2*tou&&jiao%2==0)
	{
		b=jiao/2-tou;
	a=tou-b;
	cout<<"鸡的数目为:"<<a
		<<"  兔的数目为:"<<b
		<<endl;
	}
	else
		cout<<"输入错误"<<endl;
	
	cout<<"是否继续:enter:Y or N"<<endl;
	cin>>exit;
	if(exit=='n')
		key=0;
	else
		key=1;

	}
	return 0;
}



其实除了键入“N”退出外,输入任意键都可以继续。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值