题目:
在 ISO 国际标准中定义了 A0 纸张的大小为 1189mm ×× 841mm, 将 A0 纸 沿长边对折后为 A1 纸, 大小为 841mm ×× 594mm, 在对折的过程中长度直接取 下整 (实际裁剪时可能有损耗)。将 A1 纸沿长边对折后为 A2 纸, 依此类推。
输入纸张的名称, 请输出纸张的大小。
输入格式
输入一行包含一个字符串表示纸张的名称, 该名称一定是 A0、A1、A2、 A3、A4、A5、A6、A7、A8、A9 之一。
输出格式
输出两行,每行包含一个整数,依次表示长边和短边的长度
#include <bits/stdc++.h>
#include<cmath>
using namespace std;
pair<int,int>a[10]; //用pair型数组的形式存每一个型号存对应的长宽比较方便,绑定长宽
pair<int,int>temp[10];
int main()
{
a[0].first=1189; //first永远存长
a[0].second=841; //second永远存宽
for(int i=1;i<=9;i++)
{
temp[i].first=floor((a[i-1].first)/2); //不管结果长宽,将上一次折叠的长/2
temp[i].second=a[i-1].second; //不管结果长宽,将上一次折叠的宽/2
a[i].first=max(temp[i].first,temp[i].second); //长的存入first
a[i].second=min(temp[i].first,temp[i].second); //短的存入second
}
string m; //这里不是char
cin>>m;
if(m=="A0") cout<<a[0].first<<endl<<a[0].second;
if(m=="A1") cout<<a[1].first<<endl<<a[1].second;
if(m=="A2") cout<<a[2].first<<endl<<a[2].second;
if(m=="A3") cout<<a[3].first<<endl<<a[3].second;
if(m=="A4") cout<<a[4].first<<endl<<a[4].second;
if(m=="A5") cout<<a[5].first<<endl<<a[5].second;
if(m=="A6") cout<<a[6].first<<endl<<a[6].second;
if(m=="A7") cout<<a[7].first<<endl<<a[7].second;
if(m=="A8") cout<<a[8].first<<endl<<a[8].second;
if(m=="A9") cout<<a[9].first<<endl<<a[9].second;
return 0;
}
方法改进:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char c; int x;
//先输入字符A,再输入纸张类型x
cin >> c >> x;
//维护a,b
int a = 1189, b = 841;
while(x--)
{
a /= 2;
if(a < b)swap(a, b); //巧妙运用swap函数
}
cout<<a<<endl;
cout<<b<<endl;
return 0;
}