跳出多层循环: C++输入一个面积,求长和宽,要求长宽尽量相等

小明在一家显示屏公司做设计。最近他接到了一个新的订单。订单中,顾客要求显示屏必须有n个像素。屏幕是一个长为w宽为h的矩形。顾客要求w和h要尽可能的接近(矩形要尽可能地接近一个正方形),并且w不能大于h。请你编程给出矩形的长和宽。

 

 思路是循环找出两个数相乘等于面积

#include<iostream>
#include <stdlib.h>   
using namespace std;

int main()
{
    int w,h,n,count=0;
	cin >> n;
	for(h=0;h<=n;h++)
	{
		for(w=0;w<=h;w++)
		{
				if( n==w*h )
				{
				cout << w << " " << h << endl;
				}
		}	
	}
	
	return 0;
}

发现会输出几个不同的结果,第一个才是我们需要的。因此,当有第一个输出结果时,我们要跳出两个for循环。

方法一:设置判断符

#include<iostream>
#include <stdlib.h>   
using namespace std;

int main()
{
    int w,h,n,count=0;
	cin >> n;
	for(h=0;h<=n;h++)
	{
		for(w=0;w<=h;w++)
		{
				if( n==w*h )
				{
				cout << w << " " << h << endl;
				count=1;
				}
		}
		if(count ==1)
			break;
	}
	
	return 0;
}

 方法二:修改参数使其达到最外层的循环条件从而跳出循环

#include<iostream>
#include <stdlib.h>   
using namespace std;

int main()
{
    int w,h,n,count=0;
	cin >> n;

	for(h=0;h<=n;h++)
	{
		for(w=0;w<=h;w++)
		{
				if( n==w*h )
				{
				  cout << w << " " << h << endl;
				  h=n+1;
				}
		}
	}
	

	return 0;
}

方法三 :使用goto语句

#include<iostream>
#include <stdlib.h>   
using namespace std;

int main()
{
    int w,h,n,count=0;
	cin >> n;

	for(h=0;h<=n;h++)
	{
		for(w=0;w<=h;w++)
		{
				if( n==w*h )
				{
				  cout << w << " " << h << endl;
				  goto stop;
				}
		}
	}
	stop:

	return 0;
}


方法四 使用return语句直接返回退出

#include<iostream>
#include <stdlib.h>   
using namespace std;

int main()
{
    int w,h,n,count=0;
	cin >> n;

	for(h=0;h<=n;h++)
	{
		for(w=0;w<=h;w++)
		{
				if( n==w*h )
				{
				  cout << w << " " << h << endl;
				  return 0;
				}
		}
	}

}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值