小明在一家显示屏公司做设计。最近他接到了一个新的订单。订单中,顾客要求显示屏必须有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;
}
}
}
}